file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** *Submitted for verification at Etherscan.io on 2021-09-07 */ pragma solidity ^0.5.16; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; 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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract WIHC is Context, Ownable, ERC20Interface { using SafeMath for uint256; address public admin; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address[] private _excludedTransactionFee; mapping (address => bool) private _isExcludedTransactionFee; uint256 private _totalSupply; uint8 private _decimals; string private _symbol; string private _name; constructor() public { _name = "Wrapped Inflation Hedging Coin"; _symbol = "WIHC"; _decimals = 18; _totalSupply = 50000000000 * 10 ** 18; _balances[msg.sender] = _totalSupply; admin = msg.sender; emit Transfer(address(0), msg.sender, _totalSupply); } /** * @dev Returns the token decimals. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() public view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { require(recipient != address(0), "BEP20: transfer to the zero address"); _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { require(spender != address(0), "BEP20: spender cannot be the zero address"); _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } /** * @dev set burn. */ function burn(uint256 burnAmount) external onlyOwner returns (bool) { _burn(_msgSender(), burnAmount); return true; } /** * @dev set mint. */ function mint(address _to, uint _amount) onlyOwner public returns (bool) { _mint(_msgSender(), _amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); require(msg.sender == admin, 'only admin'); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); require(msg.sender == admin, 'only admin'); _balances[account] = _balances[account].add(amount); _totalSupply = _totalSupply.add(amount); emit Transfer(address(0), account, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
See {BEP20-approve}. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 amount) public returns (bool) { require(spender != address(0), "BEP20: spender cannot be the zero address"); _approve(_msgSender(), spender, amount); return true; }
6,709,265
./full_match/1/0xD031d03E447f5873cbD44BdB75b34189829BBb93/sources/contracts/RebelMaxNFT.sol
Free for whitelisted
function reserveInPrivateSale(uint256 _amount) public nonReentrant { require(privateSale, "Private sale must be active"); require(_privateReserved[msg.sender] == 0, "Already reserved"); require(totalReserved+_amount <= (TOTAL_TOKEN_LIMIT.sub(2)), "Reserve would exceeed allocated limit."); require(_privateAddresses[msg.sender], "Not authorised to participate"); require(_amount <= _maxTokensAtOnce, "Too many tokens at once"); _privateReserved[msg.sender] = _amount; totalReserved += _amount; }
9,636,039
pragma solidity ^0.4.23; import "./ERC721.sol"; import "./ERC721BasicToken.sol"; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721HarbergerLicense is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) public ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) public ownedTokensIndex; // Mapping from token ID to index of Harlic mapping(uint256 => uint256) public tokenHarlic; // Mapping from token ID to indices of Taxlog mapping(uint256 => uint256) public tokenTaxlog; // Array with all token ids, used for enumeration uint256[] public allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) public allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) public tokenURIs; /** EVENTS **/ event Confiscation( address indexed _owner, uint256 _tokenId ); /** STRUCTS **/ struct Harlic { uint256 tokenID; uint256 turnoverRate; //turnovers per century uint256 harlicValue; //in ether uint256 publicEquity; //in wei uint256 acquisitionsCounter; //counting acquisitions address feeBeneficiary; string videoID; } struct Taxlog { uint256 tokenID; uint256 paidTaxes; //in wei uint256 incurredTaxes; //in wei uint256 lastTaxationDate; uint256 creationDate; uint256 presentTaxRate; uint256 secondlyTaxRate; } Harlic[] public harlics; Taxlog[] public taxlogs; /** * @dev Dividend Calculating Variables */ uint256 public totalKReceipts; uint256 public payoutsTotal; mapping (address => uint256) paymentsFromAddress; mapping(address => uint256) payoutsToAddress; /** * @dev Constructor function */ constructor() public { name_ = "HarbergerLicense"; symbol_ = "HARB"; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } /** * @dev Create a tokenID denoting a license * @dev Throws if the token ID already exists. * @param _to token owner * @param _tokenId token ID, must be unique * @param _turnoverRate yearly tax rate as percent. I.e.: "20" gives a twenty percent yearly rate, calculated per second. Corresponds to an asset that turns over once every five years (100/20). * @param _harlicValue value in Mether of the HarbergerLicense (harlic) * @param _publicEquity portion of the equity value, in ether, of the license that is owned by the contract/the public * @param _feeBeneficiary beneficiary of HarbergerTaxes (usually same as TokenID owner but allows assignment of revenue stream) * @param _tokenURI string name */ function publicMint( //put into the internal _mint after testing finished address _to, uint256 _tokenId, uint256 _turnoverRate, uint256 _harlicValue, uint256 _publicEquity, //should be zero unless user donating to public address _feeBeneficiary, string _tokenURI, string _videoID) public returns (bool) { require(_turnoverRate >= 0); // as percentage require(_publicEquity >= 0 && _publicEquity <= 100); // require percentage Harlic memory _harlic = Harlic({ tokenID: _tokenId, turnoverRate: _turnoverRate, harlicValue: _harlicValue, publicEquity: _publicEquity, feeBeneficiary: _feeBeneficiary, acquisitionsCounter: 0, videoID: _videoID }); harlics.push(_harlic) - 1; //create harlic struct for token Taxlog memory _taxlog = Taxlog({ tokenID: _tokenId, paidTaxes: 0, incurredTaxes: 0, creationDate: now, lastTaxationDate: now, presentTaxRate: _turnoverRate, secondlyTaxRate: 0 }); taxlogs.push(_taxlog) - 1; //create taxlog struct for token tokenTaxlog[_tokenId] = taxlogs.length - 1; //make record of associated taxlog tokenHarlic[_tokenId] = harlics.length - 1; //make record of associated harlic _mint(_to, _tokenId); //create token _setTokenURI(_tokenId, _tokenURI); //set URI } /** * @dev report new self-assessed value * @dev new per-second tax rate immediately goes into effect. * @dev causes previous tax rate to "accrue", i.e. be calculated by the calculateTax function * @param _tokenId token ID, must be owned by you * @param _value new value */ function selfAssess (uint256 _tokenId, uint256 _value) public onlyOwnerOf(_tokenId) returns (bool) { assessTax(_tokenId); /*prevent out-of-chronological-order assessments*/ require(taxlogs[tokenIndex].lastTaxationDate <= now, "Assessment cannot happen until after lastTaxationDate"); /*update self-assessed value*/ uint256 tokenIndex = allTokensIndex[_tokenId]; harlics[tokenIndex].harlicValue = _value; } function changeVideo (uint256 _tokenId, string _videoID) public onlyOwnerOf(_tokenId) returns (bool) { /*update self-assessed value*/ uint256 tokenIndex = allTokensIndex[_tokenId]; harlics[tokenIndex].videoID = _videoID; } function reaffirmValue (uint256 _tokenId) //doesnt require owner of token to call internal returns (bool) { /*prevent out-of-chronological-order assessments*/ require(taxlogs[tokenIndex].lastTaxationDate <= now, "Assessment cannot happen until after lastTaxationDate"); /*update self-assessed value with same value*/ uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 sameValue = harlics[tokenIndex].harlicValue; harlics[tokenIndex].harlicValue = sameValue; } /** * @dev calculate accrued tax, paid or not--i.e. all taxes outside of the period formed by the most recent self-valuation */ function calculateTax(uint256 _tokenId) public returns (uint256) { /*tax calculation, working*/ require(exists(_tokenId) == true); uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 taxSinceLastAssessment; uint256 periodValuationMEther = SafeMath.mul(harlics[tokenIndex].harlicValue, 1000000000000000); uint256 periodLengthSeconds = SafeMath.sub(now, taxlogs[tokenIndex].lastTaxationDate); // in seconds uint256 totalTurnovers = harlics[tokenIndex].acquisitionsCounter; if (totalTurnovers == 0) { uint256 weiPerSecondTax = SafeMath.mul(SafeMath.div(periodValuationMEther, SafeMath.mul(3153600000, harlics[tokenIndex].turnoverRate)), 1000000); //seconds in century / turnovers in century uint256 creatorIncentive = 0; } else { weiPerSecondTax = SafeMath.mul(SafeMath.div(periodValuationMEther, SafeMath.mul(3153600000, harlics[tokenIndex].turnoverRate)), 1000000); //seconds in century / turnovers in century creatorIncentive = SafeMath.sub(1000000000000000000, SafeMath.div(1000000000000000000, harlics[tokenIndex].acquisitionsCounter)); } uint256 decayedWeiPerSecondTax = SafeMath.div(SafeMath.mul(weiPerSecondTax, creatorIncentive), 1000000000000000000); taxlogs[tokenIndex].presentTaxRate = weiPerSecondTax; //update taxrate //taxlogs[tokenIndex].yearlyTurnovers = turnoversPerYear; taxlogs[tokenIndex].secondlyTaxRate = decayedWeiPerSecondTax; taxSinceLastAssessment = SafeMath.mul(decayedWeiPerSecondTax, periodLengthSeconds); //deflating //taxlogs[tokenIndex].incurredTaxes = allTimeTax; return (taxSinceLastAssessment); } /** * @dev force-acquire token. value sent must equal or exceed current value of token less owner's current unpaid taxes */ function acquireToken (uint256 _tokenId) public payable returns (bool) { assessTax(_tokenId); //update publicEquity value attaching to tokenId's harlic uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 latestSelfAssesedValue = harlics[tokenIndex].harlicValue; uint256 acquisitionPrice = SafeMath.sub(SafeMath.mul(latestSelfAssesedValue, 1000000000000000), harlics[tokenIndex].publicEquity); //require acquiror to send harlic value less privateEquity to contract; this value to be forwarded to oldOwner uint256 taxPayment = SafeMath.sub(msg.value, acquisitionPrice); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; require(msg.value >= acquisitionPrice, "You tried to send less than the acquisition price. Transaction reverted."); //require(msg.value <= latestSelfAssesedValue, //"You tried to send more than the value of the asset. Transaction reverted."); require(oldOwner != address(0)); require(newOwner != address(0)); clearApproval(oldOwner, _tokenId); removeTokenFrom(oldOwner, _tokenId); addTokenTo(newOwner, _tokenId); harlics[tokenIndex].acquisitionsCounter ++; //internal payTax function that applies sent value minus acquisition price to taxes applyAcquisitionPaymentToTax(_tokenId, taxPayment); trackPayments(newOwner, taxPayment); //test: oldOwner.transfer(acquisitionPrice); selfAssess(_tokenId, latestSelfAssesedValue); //reassess token at same value emit Transfer(oldOwner, newOwner, _tokenId); } /** * @dev Public function causing the confiscation of publicEquity corresponding to all tokenOwner's past due taxes * @dev Sets the value of publicEquity of each harlic to the current level of unpaid taxes */ // function confiscateAllPublicEquity () // public returns (bool) { // //loop through all tokens // } /** * @dev Confiscate token with PublicEquity >= 1ETH */ function confiscateToken (uint _tokenID) public returns (bool) { uint256 tokenIndex = allTokensIndex[_tokenID]; bool delinquent = (harlics[tokenIndex].publicEquity > 1); address owner = ownerOf(_tokenID); if (delinquent == true) { harlics[tokenIndex].harlicValue = 0; harlics[tokenIndex].publicEquity = 0; harlics[tokenIndex].videoID = "DRVptF3MG4g"; taxlogs[tokenIndex].paidTaxes = 0; taxlogs[tokenIndex].paidTaxes = 0; taxlogs[tokenIndex].incurredTaxes = 0; taxlogs[tokenIndex].secondlyTaxRate = 0; } emit Confiscation(owner, _tokenID); } /** * @dev Public function causing the confiscation of publicEquity corresponding to particular token * @dev Sets the value of publicEquity of tokenId's harlic to the current level of unpaid taxes * @dev TODO: cause this to presently re-appraise the token at the current value so that recent unpaid taxes accrue. */ function assessTax (uint256 _tokenId) public returns (uint256, uint256, uint256) { uint256 index = allTokensIndex[_tokenId]; uint256 taxSinceLastAssessment = calculateTax(_tokenId); taxlogs[index].incurredTaxes += taxSinceLastAssessment; uint256 paidTaxes = taxlogs[index].paidTaxes; uint256 owedTaxes = (taxlogs[index].incurredTaxes - paidTaxes); // not in SafeMath because 0 - 0 was throwing for some reasons uint256 publicEquity = owedTaxes; //absolute (wei) publicEquity harlics[index].publicEquity = publicEquity; //reset lastTaxationDate taxlogs[index].lastTaxationDate = now; return (paidTaxes, owedTaxes, publicEquity); } /** * @dev value sent with function applied against taxes */ function payTax (uint256 _tokenId) public payable returns (bool) { uint256 index = allTokensIndex[_tokenId]; assessTax(_tokenId); uint256 oldOwedTaxes = SafeMath.sub(taxlogs[index].incurredTaxes, taxlogs[index].paidTaxes); require(msg.value <= oldOwedTaxes, "You must not send more than the amount of tax you owe. You should send a bit less than the amount you owe."); taxlogs[index].paidTaxes += msg.value; uint256 newOwedTaxes = SafeMath.sub(taxlogs[index].incurredTaxes, taxlogs[index].paidTaxes); harlics[index].publicEquity = newOwedTaxes; } function applyAcquisitionPaymentToTax (uint256 _tokenId, uint256 _taxPayment) internal returns (bool) { uint256 index = allTokensIndex[_tokenId]; taxlogs[index].paidTaxes += _taxPayment; harlics[index].publicEquity -= _taxPayment; } /**CUSTOM GETTERS**/ function getAcquisitionPrice (uint256 _tokenId) public returns (uint256) { assessTax(_tokenId); //update publicEquity value attaching to tokenId's harlic uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 acquisitionPrice = SafeMath.sub(SafeMath.mul(harlics[tokenIndex].harlicValue, 1000000000000000), harlics[tokenIndex].publicEquity); return acquisitionPrice; } function simplePrice (uint256 _tokenId) public view returns (uint256 tIndex, uint256 harlicVal, uint256 pEquity, uint256 aPrice) { uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 harlicValue = harlics[tokenIndex].harlicValue; uint256 publicEquity = harlics[tokenIndex].publicEquity; uint256 acquisitionPrice = SafeMath.sub(SafeMath.mul(harlics[tokenIndex].harlicValue, 1000000000000000), harlics[tokenIndex].publicEquity); return (tokenIndex, harlicValue, publicEquity, acquisitionPrice); } function() public payable { } function trackPayments(address _address, uint256 _amountIn) internal { totalKReceipts += _amountIn; paymentsFromAddress[_address] += _amountIn; } }
require(msg.value <= latestSelfAssesedValue,"You tried to send more than the value of the asset. Transaction reverted.");internal payTax function that applies sent value minus acquisition price to taxestest:
function acquireToken (uint256 _tokenId) public payable returns (bool) { uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 latestSelfAssesedValue = harlics[tokenIndex].harlicValue; uint256 taxPayment = SafeMath.sub(msg.value, acquisitionPrice); address oldOwner = ownerOf(_tokenId); address newOwner = msg.sender; require(msg.value >= acquisitionPrice, "You tried to send less than the acquisition price. Transaction reverted."); require(oldOwner != address(0)); require(newOwner != address(0)); clearApproval(oldOwner, _tokenId); removeTokenFrom(oldOwner, _tokenId); addTokenTo(newOwner, _tokenId); harlics[tokenIndex].acquisitionsCounter ++; applyAcquisitionPaymentToTax(_tokenId, taxPayment); trackPayments(newOwner, taxPayment); oldOwner.transfer(acquisitionPrice); emit Transfer(oldOwner, newOwner, _tokenId); }
12,887,891
// SPDX-License-Identifier: MIT // Project Sharing by Alpha Serpentis Developments - https://github.com/Alpha-Serpentis-Developments // Written by Amethyst C. pragma solidity ^0.7.4; import "../ERC677/ERC677Receiver.sol"; import "../ERC677/ERC677.sol"; import "../Module/Module.sol"; import "../../openzeppelin/math/SafeMath.sol"; import "../../openzeppelin/token/ERC20/IERC20.sol"; import "../../openzeppelin/token/ERC20/SafeERC20.sol"; contract Caring is ERC677Receiver { using SafeERC20 for IERC20; using SafeMath for uint256; struct ModuleRequest { address module; // Address of the module to add address proposer; // Address of the proposer uint64 automaticPass; // UNIX time when the module request is automatically passed address[] approved; // Addresses of managers who accepted } struct TransferRequest { address member; // Address of the member requesting address payable to; // Address of the receiving party address token; // If applicable uint256 amount; // Amount of tokens withdrawing bytes32 ident; // The identifier of the TransferRequest address[] approved; // Current approvals address[] rejected; // Current rejected bytes data; // Data if any bool exists; // Used to know if it exists in the mapping or not } struct Member { address adr; // Address of the member bool isManager; // Is a manager of the wallet bool allowedToDeposit; // Is allowed to deposit bool allowedToWithdraw; // Is allowed to withdraw } mapping(address => Member) private members; mapping(bytes32 => TransferRequest) private pendingOutbound; mapping(address => uint256) private userNonce; mapping(address => ModuleRequest) private pendingModules; mapping(address => bool) private authorizedModules; bytes public identifier; bool private multiSig; bool private allowModules; bool private publicDeposit; uint256 private immutable MAX_ALLOWED_MANAGERS; uint256 private totalManagers; uint256 private totalMembers; uint256 private minimumSig; uint256 private moduleAutoAcceptLength; uint256 private pendingTransfers; // Events event Deposit(address _from, uint256 amount); event PendingTransfer(address _from, address _to, address _token, uint256 _amount, uint256 _nonce, bytes32 _transferId); event TransferCancelled(address _from, bytes32 _transferId); event TransferExecute(address _from, address _to, address _token, bool _success); event Withdrawal(address _from, address _to, uint256 _amount); event PendingModule(address _module, address _proposer, uint256 _acceptAtUnix); event ModuleAdded(address _module); event ModuleRemoved(address _module); event ModuleAdditionCancelled(address _module, address _proposer); constructor( address _manager, uint256 _maxManagers, bytes memory _contractName, bool _multiSig, uint256 _moduleAutoAcceptLength) { require( _manager != address(0), "Caring: Must have a manager!" ); require( _maxManagers > 0 && _maxManagers < (2**256) - 1, "Caring: Must have at least one manager (this includes yourself)!" ); require( bytes(_contractName).length != 0, "Caring: Must have a contract identifier!" ); require( _moduleAutoAcceptLength < (2**256) - 1, "Caring: Invalid _moduleAutoAcceptLength value passed!" ); MAX_ALLOWED_MANAGERS = _maxManagers; identifier = _contractName; totalManagers = 1; totalMembers = 1; multiSig = _multiSig; allowModules = false; minimumSig = 1; moduleAutoAcceptLength = _moduleAutoAcceptLength; members[_manager].adr = _manager; members[_manager].isManager = true; members[_manager].allowedToDeposit = true; members[_manager].allowedToWithdraw = true; } modifier onlyManager { verifyOnlyManager(); _; } modifier onlyMember { verifyOnlyMember(); _; } modifier publicDepositCheck { verifyPublicDeposit(); _; } receive() payable external publicDepositCheck { // This does not reject mined Ether or from a selfdestruct emit Deposit(msg.sender, msg.value); } // TRANSFER FUNCTIONS function requestTransfer( address payable _to, address _token, uint256 _amount ) public onlyMember returns(bytes32) { if(_token == address(0)) { require( address(this).balance >= _amount, "requestTransfer(): Insufficient funds to withdraw!" ); } else { IERC20 token; token = IERC20(_token); require( token.balanceOf(_token) >= _amount, "requestTransfer(): Insufficient funds to withdraw!" ); } bytes32 transferId; transferId = keccak256( abi.encode( msg.sender, _to, _token, _amount, userNonce[msg.sender]++ ) ); TransferRequest memory transferReq; transferReq.member = msg.sender; transferReq.to = _to; transferReq.token = _token; transferReq.amount = _amount; if(multiSig) { addPendingTx(transferReq); emit PendingTransfer( msg.sender, _to, _token, _amount, userNonce[msg.sender] - 1, transferId ); } else { executeSomeTx(transferReq); } return transferId; } function approveTransfer( bytes32 _index, bool _approve ) public onlyMember { require( multiSig, "approveTransfer(): Can only be used if multi-sig mode is enabled!" ); TransferRequest storage transferReq = pendingOutbound[_index]; // Approve or deny the transaction if(_approve) { transferReq.approved.push(msg.sender); } else { transferReq.rejected.push(msg.sender); } // Check if able to execute or has failed the 51%+ requirement verifyMultiSig(transferReq); } function attemptTransfer(bytes32 _index) public onlyMember { verifyMultiSig(pendingOutbound[_index]); } function manualCancelTransfer(bytes32 _index) public onlyMember { require( pendingOutbound[_index].member == msg.sender, "manualCancelTransfer(): Must be the member initiating the transfer request to cancel!" ); removePendingTx(_index); emit TransferCancelled( pendingOutbound[_index].member, _index ); } function onTokenTransfer( address _from, uint256 _amount, bytes memory _data ) public override publicDepositCheck returns(bool success) { } // MEMBER MANAGEMENT FUNCTIONS function addMember( address _member, bool _allowDeposit, bool _allowWithdrawal ) public onlyManager { members[_member].adr = _member; members[_member].allowedToDeposit = _allowDeposit; members[_member].allowedToWithdraw = _allowWithdrawal; totalMembers++; } function removeMember(address _member) public onlyManager { delete members[_member]; totalMembers--; } function addManager(address _newManager) public onlyManager { require( totalManagers < MAX_ALLOWED_MANAGERS, "addManager(): Maximum managers reached!" ); if(members[_newManager].adr == address(0)) { addMember(_newManager, true, true); } members[_newManager].isManager = true; totalManagers++; } function removeManager(address _manager) public onlyManager { require( msg.sender != _manager, "removeManager(): Cannot remove manager from yourself!" ); members[_manager].isManager = false; totalManagers--; } // MODULE FUNCTIONS function addModule(address _module) public onlyManager { require( _module != address(0), "addModule(): Invalid module address!" ); ModuleRequest memory moduleReq; moduleReq.module = _module; moduleReq.proposer = msg.sender; moduleReq.automaticPass = uint64( block.timestamp.add(moduleAutoAcceptLength) ); pendingModules[_module] = moduleReq; emit PendingModule( _module, msg.sender, moduleReq.automaticPass ); } function removeModule(address _module) public onlyManager { require( _module != address(0), "removeModule(): Invalid module address!" ); require( authorizedModules[_module], "removeModule(): Module is not authorized (therefore it cannot be removed)!" ); delete authorizedModules[_module]; } function expediteModuleAddition(address _module) public onlyManager { require( _module != address(0), "expediteModuleAddition(): Invalid module address!" ); require( pendingModules[_module].approved.length == totalManagers, "expediteModuleAddition(): Cannot be expedited; not enough approvals" ); authorizeModule(_module); } function approvePendingModule(address _module) public onlyManager { require( _module != address(0), "approvePendingModule(): Invalid module address!" ); require( pendingModules[_module].module != address(0), "approvePendingModule(): Module is not pending/DNE" ); pendingModules[_module].approved.push(msg.sender); } function cancelPendingModule(address _module) public onlyManager { require( _module != address(0), "cancelPendingModule(): Invalid module address!" ); // Check if you can still cancel the pending module ModuleRequest memory pending = pendingModules[_module]; if(pending.automaticPass >= block.timestamp) { // Will pass, even if you wanted to cancel authorizeModule(_module); } else { delete pendingModules[_module]; } } function interactWithModule(address _module, bytes memory _data) external onlyMember returns(bool success, bytes memory returnData) { require( _module != address(0), "Module cannot be 0 address!" ); require( authorizedModules[_module], "interactWithModule(): Not authorized" ); Module interactWith = Module(_module); interactWith.execute(_data); } // SIMPLE SETTER FUNCTIONS function setMemberAllowedToDeposit( address _member, bool _allowed ) public onlyManager { members[_member].allowedToDeposit = _allowed; } function setMemberAllowedToWithdraw( address _member, bool _allowed ) public onlyManager { members[_member].allowedToWithdraw = _allowed; } function setMultiSig( bool _enable ) public onlyManager { multiSig = _enable; } function setMinimumMultiSig( uint256 _amount, bool _useSuggested ) public onlyManager { require( _amount <= totalMembers && _amount > 0, "setMinimumMultiSig(): Invalid minimum multi-signature" ); if(_useSuggested) minimumSig = suggestedSigners(totalMembers); else minimumSig = _amount; // This does NOT check if it passes a 50%... } // MISC FUNCTIONS function suggestedSigners( uint256 _count ) public pure returns(uint256) { require( _count > 0 && _count < (2**256) - 1, "suggestedSigners(): Invalid '_count' value!" ); //recommended = _count/2 + _count%2; uint256 recommended = _count.div(2).add(_count.mod(2)); return recommended; } function getIdentifier() public view returns(bytes memory) { return identifier; } function getTotalMembers() public view returns(uint256) { return totalMembers; } function isMultiSig() public view returns(bool) { return multiSig; } function getMinimumSig() public view returns(uint256) { return minimumSig; } function getPendingTransferCount() public view returns(uint256) { return pendingTransfers; } function isMember(address _address) public view returns(bool) { return members[_address].adr != address(0); } function isMemberAllowedToDeposit(address _address) public view returns(bool) { return members[_address].allowedToDeposit; } function isMemberAllowedToWithdraw(address _address) public view returns(bool) { return members[_address].allowedToWithdraw; } function isManager(address _address) public view returns(bool) { return members[_address].isManager; } // INTERNAL FUNCTIONS function verifyPublicDeposit() internal view { if(publicDeposit) { verifyOnlyMember(); } } function verifyOnlyMember() internal view { require( members[msg.sender].adr != address(0), "onlyMember: Must be a member!" ); } function verifyOnlyManager() internal view { require( members[msg.sender].isManager, "onlyManager: Must be the manager!" ); } function verifyMultiSig(TransferRequest memory _tx) internal { if(_tx.approved.length >= minimumSig) {// If passes definitely, execute transfer executeSomeTx(_tx); } else if(totalMembers.sub(_tx.rejected.length) < minimumSig) { // If fails definitely, cancel the transfer removePendingTx(_tx.ident); emit TransferCancelled( pendingOutbound[_tx.ident].member, _tx.ident ); } } function addPendingTx(TransferRequest memory _tx) internal { pendingOutbound[_tx.ident] = _tx; } function removePendingTx(bytes32 _ident) internal { delete pendingOutbound[_ident]; } function executeSomeTx(TransferRequest memory _tx) internal { if(_tx.token == address(0)) executeEtherTx(_tx); else executeTokenTx(_tx); } function executeEtherTx(TransferRequest memory _tx) internal { if(pendingOutbound[_tx.ident].exists) { require( pendingOutbound[_tx.ident].amount <= address(this).balance, "executeEtherTx(): Cannot withdraw more than there actually is!" ); pendingOutbound[_tx.ident].to.transfer(pendingOutbound[_tx.ident].amount); emit TransferExecute( pendingOutbound[_tx.ident].member, pendingOutbound[_tx.ident].to, address(0), true ); removePendingTx(_tx.ident); } } function executeTokenTx(TransferRequest memory _tx) internal { ERC677 _token = ERC677(_tx.token); try _token.transferAndCall(_tx.to, _tx.amount, _tx.data) { } catch { // Perform fallback IERC20 _fallbackToken = IERC20(_tx.token); _fallbackToken.safeTransfer(_tx.to, _tx.amount); } removePendingTx(_tx.ident); } function authorizeModule(address _module) internal { require( _module != address(0), "authorizeModule: zero address" ); authorizedModules[_module] = true; delete pendingModules[_module]; } }
Approve or deny the transaction
{ require( multiSig, "approveTransfer(): Can only be used if multi-sig mode is enabled!" ); TransferRequest storage transferReq = pendingOutbound[_index]; function approveTransfer( bytes32 _index, bool _approve ) public onlyMember if(_approve) { transferReq.approved.push(msg.sender); transferReq.rejected.push(msg.sender); } } else { verifyMultiSig(transferReq); }
5,448,564
pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); 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; } } // ERC20 token interface is implemented only partially. interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract NamiPool { using SafeMath for uint256; function NamiPool(address _escrow, address _namiMultiSigWallet, address _namiAddress) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; NamiAddr = _namiAddress; } string public name = "Nami Pool"; // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; /// address of Nami token address public NamiAddr; modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyNami { require(msg.sender == NamiAddr); _; } modifier onlyNamiMultisig { require(msg.sender == namiMultiSigWallet); _; } uint public currentRound = 1; struct ShareHolder { uint stake; bool isActive; bool isWithdrawn; } struct Round { bool isOpen; uint currentNAC; uint finalNAC; uint ethBalance; bool withdrawable; //for user not in top bool topWithdrawable; bool isCompleteActive; bool isCloseEthPool; } mapping (uint => mapping (address => ShareHolder)) public namiPool; mapping (uint => Round) public round; // Events event UpdateShareHolder(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Stake, uint Time); event Deposit(address sender,uint indexed RoundIndex, uint value); event WithdrawPool(uint Amount, uint TimeWithdraw); event UpdateActive(address indexed ShareHolderAddress, uint indexed RoundIndex, bool Status, uint Time); event Withdraw(address indexed ShareHolderAddress, uint indexed RoundIndex, uint Ether, uint Nac, uint TimeWithdraw); event ActivateRound(uint RoundIndex, uint TimeActive); function changeEscrow(address _escrow) onlyNamiMultisig public { require(_escrow != 0x0); escrow = _escrow; } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function withdrawNAC(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0 && _amount != 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); if (namiToken.balanceOf(this) > 0) { namiToken.transfer(namiMultiSigWallet, _amount); } } /*/ * Admin function /*/ /*/ process of one round * step 1: admin open one round by execute activateRound function * step 2: now investor can invest Nac to Nac Pool until round closed * step 3: admin close round, now investor cann&#39;t invest NAC to Pool * step 4: admin activate top investor * step 5: all top investor was activated, admin execute closeActive function to close active phrase * step 6: admin open withdrawable for investor not in top to withdraw NAC * step 7: admin deposit eth to eth pool * step 8: close deposit eth to eth pool * step 9: admin open withdrawable to investor in top * step 10: investor in top now can withdraw NAC and ETH for this round /*/ // ------------------------------------------------ /* * Admin function * Open and Close Round * */ function activateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == false && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == false); round[_roundIndex].isOpen = true; currentRound = _roundIndex; ActivateRound(_roundIndex, now); } function deactivateRound(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isOpen == true); round[_roundIndex].isOpen = false; } // ------------------------------------------------ // this function add stake of ShareHolder // investor can execute this function during round open // function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { // only on currentRound and active user can add stake require(round[_price].isOpen == true && _value > 0); // add stake namiPool[_price][_from].stake = namiPool[_price][_from].stake.add(_value); round[_price].currentNAC = round[_price].currentNAC.add(_value); UpdateShareHolder(_from, _price, namiPool[_price][_from].stake, now); return true; } /* * * Activate and deactivate user * add or sub final Nac to compute stake to withdraw */ function activateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == false && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = true; round[_roundId].finalNAC = round[_roundId].finalNAC.add(namiPool[_roundId][_shareAddress].stake); UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } function deactivateUser(address _shareAddress, uint _roundId) onlyEscrow public { require(namiPool[_roundId][_shareAddress].isActive == true && namiPool[_roundId][_shareAddress].stake > 0); require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); namiPool[_roundId][_shareAddress].isActive = false; round[_roundId].finalNAC = round[_roundId].finalNAC.sub(namiPool[_roundId][_shareAddress].stake); UpdateActive(_shareAddress, _roundId ,namiPool[_roundId][_shareAddress].isActive, now); } // ------------------------------------------------ // admin close activate phrase to // // function closeActive(uint _roundId) onlyEscrow public { require(round[_roundId].isCompleteActive == false && round[_roundId].isOpen == false); round[_roundId].isCompleteActive = true; } // // // change Withdrawable for one round after every month // for investor not in top // function changeWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].withdrawable = !round[_roundIndex].withdrawable; } // // // change Withdrawable for one round after every month // for investor in top // function changeTopWithdrawable(uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].topWithdrawable = !round[_roundIndex].topWithdrawable; } // // // after month admin deposit ETH to ETH Pool // // function depositEthPool(uint _roundIndex) payable public onlyEscrow { require(msg.value > 0 && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); if (msg.value > 0) { round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.add(msg.value); Deposit(msg.sender, _roundIndex, msg.value); } } // // function withdrawEthPool(uint _roundIndex, uint _amount) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); require(namiMultiSigWallet != 0x0); // if (_amount > 0) { namiMultiSigWallet.transfer(_amount); round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.sub(_amount); WithdrawPool(_amount, now); } } // // close phrase deposit ETH to Pool // function closeEthPool(uint _roundIndex) public onlyEscrow { require(round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); round[_roundIndex].isCloseEthPool = true; } // // // withdraw NAC for investor // internal function only can run by this smartcontract // // function _withdrawNAC(address _shareAddress, uint _roundIndex) internal { require(namiPool[_roundIndex][_shareAddress].stake > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(this); namiToken.transfer(_shareAddress, namiPool[_roundIndex][_shareAddress].stake); // update current Nac pool balance round[_roundIndex].currentNAC = round[_roundIndex].currentNAC.sub(namiPool[_roundIndex][_shareAddress].stake); namiPool[_roundIndex][_shareAddress].stake = 0; assert(previousBalances > namiToken.balanceOf(this)); } // // // withdraw NAC and ETH for top investor // // function withdrawTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == true) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); assert(round[_roundIndex].finalNAC > namiPool[_roundIndex][_shareAddress].stake); // compute eth for invester uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][_shareAddress].stake)).div(round[_roundIndex].finalNAC); _shareAddress.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; Withdraw(_shareAddress, _roundIndex, ethReturn, namiPool[_roundIndex][_shareAddress].stake, now); // withdraw NAC _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by admin only // // function withdrawNonTopForTeam(address _shareAddress, uint _roundIndex) onlyEscrow public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][_shareAddress].isActive == false) { require(namiPool[_roundIndex][_shareAddress].isWithdrawn == false); // set state user withdraw namiPool[_roundIndex][_shareAddress].isWithdrawn = true; Withdraw(_shareAddress, _roundIndex, 0, namiPool[_roundIndex][_shareAddress].stake, now); // _withdrawNAC(_shareAddress, _roundIndex); } } // // // withdraw NAC and ETH for top investor // execute by investor // // function withdrawTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isCloseEthPool == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].topWithdrawable); if(namiPool[_roundIndex][msg.sender].isActive == true) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); uint ethReturn = (round[_roundIndex].ethBalance.mul(namiPool[_roundIndex][msg.sender].stake)).div(round[_roundIndex].finalNAC); msg.sender.transfer(ethReturn); // set user withdraw namiPool[_roundIndex][msg.sender].isWithdrawn = true; // Withdraw(msg.sender, _roundIndex, ethReturn, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } // // // withdraw NAC and ETH for non top investor // execute by investor // // function withdrawNonTop(uint _roundIndex) public { require(round[_roundIndex].isCompleteActive == true && round[_roundIndex].isOpen == false); require(round[_roundIndex].withdrawable); if(namiPool[_roundIndex][msg.sender].isActive == false) { require(namiPool[_roundIndex][msg.sender].isWithdrawn == false); namiPool[_roundIndex][msg.sender].isWithdrawn = true; // Withdraw(msg.sender, _roundIndex, 0, namiPool[_roundIndex][msg.sender].stake, now); _withdrawNAC(msg.sender, _roundIndex); } } } contract NamiCrowdSale { using SafeMath for uint256; /// NAC Broker Presale Token /// @dev Constructor function NamiCrowdSale(address _escrow, address _namiMultiSigWallet, address _namiPresale) public { require(_namiMultiSigWallet != 0x0); escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; namiPresale = _namiPresale; } /*/ * Constants /*/ string public name = "Nami ICO"; string public symbol = "NAC"; uint public decimals = 18; bool public TRANSFERABLE = false; // default not transferable uint public constant TOKEN_SUPPLY_LIMIT = 1000000000 * (1 ether / 1 wei); uint public binary = 0; /*/ * Token state /*/ enum Phase { Created, Running, Paused, Migrating, Migrated } Phase public currentPhase = Phase.Created; uint public totalSupply = 0; // amount of tokens already sold // escrow has exclusive priveleges to call administrative // functions on this contract. address public escrow; // Gathered funds can be withdraw only to namimultisigwallet&#39;s address. address public namiMultiSigWallet; // nami presale contract address public namiPresale; // Crowdsale manager has exclusive priveleges to burn presale tokens. address public crowdsaleManager; // binary option address address public binaryAddress; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; modifier onlyCrowdsaleManager() { require(msg.sender == crowdsaleManager); _; } modifier onlyEscrow() { require(msg.sender == escrow); _; } modifier onlyTranferable() { require(TRANSFERABLE); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } /*/ * Events /*/ event LogBuy(address indexed owner, uint value); event LogBurn(address indexed owner, uint value); event LogPhaseSwitch(Phase newPhase); // Log migrate token event LogMigrate(address _from, address _to, uint256 amount); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); /*/ * Public functions /*/ /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } // Transfer the balance from owner&#39;s account to another account // only escrow can send token (to send token private sale) function transferForTeam(address _to, uint256 _value) public onlyEscrow { _transfer(msg.sender, _to, _value); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public onlyTranferable { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public onlyTranferable returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public onlyTranferable returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public onlyTranferable returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // allows transfer token function changeTransferable () public onlyEscrow { TRANSFERABLE = !TRANSFERABLE; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // change binary value function changeBinary(uint _binary) public onlyEscrow { binary = _binary; } // change binary address function changeBinaryAddress(address _binaryAddress) public onlyEscrow { require(_binaryAddress != 0x0); binaryAddress = _binaryAddress; } /* * price in ICO: * first week: 1 ETH = 2400 NAC * second week: 1 ETH = 23000 NAC * 3rd week: 1 ETH = 2200 NAC * 4th week: 1 ETH = 2100 NAC * 5th week: 1 ETH = 2000 NAC * 6th week: 1 ETH = 1900 NAC * 7th week: 1 ETH = 1800 NAC * 8th week: 1 ETH = 1700 nac * time: * 1517443200: Thursday, February 1, 2018 12:00:00 AM * 1518048000: Thursday, February 8, 2018 12:00:00 AM * 1518652800: Thursday, February 15, 2018 12:00:00 AM * 1519257600: Thursday, February 22, 2018 12:00:00 AM * 1519862400: Thursday, March 1, 2018 12:00:00 AM * 1520467200: Thursday, March 8, 2018 12:00:00 AM * 1521072000: Thursday, March 15, 2018 12:00:00 AM * 1521676800: Thursday, March 22, 2018 12:00:00 AM * 1522281600: Thursday, March 29, 2018 12:00:00 AM */ function getPrice() public view returns (uint price) { if (now < 1517443200) { // presale return 3450; } else if (1517443200 < now && now <= 1518048000) { // 1st week return 2400; } else if (1518048000 < now && now <= 1518652800) { // 2nd week return 2300; } else if (1518652800 < now && now <= 1519257600) { // 3rd week return 2200; } else if (1519257600 < now && now <= 1519862400) { // 4th week return 2100; } else if (1519862400 < now && now <= 1520467200) { // 5th week return 2000; } else if (1520467200 < now && now <= 1521072000) { // 6th week return 1900; } else if (1521072000 < now && now <= 1521676800) { // 7th week return 1800; } else if (1521676800 < now && now <= 1522281600) { // 8th week return 1700; } else { return binary; } } function() payable public { buy(msg.sender); } function buy(address _buyer) payable public { // Available only if presale is running. require(currentPhase == Phase.Running); // require ICO time or binary option require(now <= 1522281600 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); // add new token to buyer balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); // add new token to totalSupply totalSupply = totalSupply.add(newTokens); LogBuy(_buyer,newTokens); Transfer(this,_buyer,newTokens); } /// @dev Returns number of tokens owned by given address. /// @param _owner Address of token owner. function burnTokens(address _owner) public onlyCrowdsaleManager { // Available only during migration phase require(currentPhase == Phase.Migrating); uint tokens = balanceOf[_owner]; require(tokens != 0); balanceOf[_owner] = 0; totalSupply -= tokens; LogBurn(_owner, tokens); Transfer(_owner, crowdsaleManager, tokens); // Automatically switch phase when migration is done. if (totalSupply == 0) { currentPhase = Phase.Migrated; LogPhaseSwitch(Phase.Migrated); } } /*/ * Administrative functions /*/ function setPresalePhase(Phase _nextPhase) public onlyEscrow { bool canSwitchPhase = (currentPhase == Phase.Created && _nextPhase == Phase.Running) || (currentPhase == Phase.Running && _nextPhase == Phase.Paused) // switch to migration phase only if crowdsale manager is set || ((currentPhase == Phase.Running || currentPhase == Phase.Paused) && _nextPhase == Phase.Migrating && crowdsaleManager != 0x0) || (currentPhase == Phase.Paused && _nextPhase == Phase.Running) // switch to migrated only if everyting is migrated || (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated && totalSupply == 0); require(canSwitchPhase); currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } function setCrowdsaleManager(address _mgr) public onlyEscrow { // You can&#39;t change crowdsale contract when migration is in progress. require(currentPhase != Phase.Migrating); crowdsaleManager = _mgr; } // internal migrate migration tokens function _migrateToken(address _from, address _to) internal { PresaleToken presale = PresaleToken(namiPresale); uint256 newToken = presale.balanceOf(_from); require(newToken > 0); // burn old token presale.burnTokens(_from); // add new token to _to balanceOf[_to] = balanceOf[_to].add(newToken); // add new token to totalSupply totalSupply = totalSupply.add(newToken); LogMigrate(_from, _to, newToken); Transfer(this,_to,newToken); } // migate token function for Nami Team function migrateToken(address _from, address _to) public onlyEscrow { _migrateToken(_from, _to); } // migrate token for investor function migrateForInvestor() public { _migrateToken(msg.sender, msg.sender); } // Nami internal exchange // event for Nami exchange event TransferToBuyer(address indexed _from, address indexed _to, uint _value, address indexed _seller); event TransferToExchange(address indexed _from, address indexed _to, uint _value, uint _price); /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackExchange` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackExchange` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _price price to sell token. */ function transferToExchange(address _to, uint _value, uint _price) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackExchange(msg.sender, _value, _price); TransferToExchange(msg.sender, _to, _value, _price); } } /** * @dev Transfer the specified amount of tokens to the NamiExchange address. * Invokes the `tokenFallbackBuyer` function. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallbackBuyer` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _buyer address of seller. */ function transferToBuyer(address _to, uint _value, address _buyer) public { uint codeLength; assembly { codeLength := extcodesize(_to) } balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); Transfer(msg.sender,_to,_value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallbackBuyer(msg.sender, _value, _buyer); TransferToBuyer(msg.sender, _to, _value, _buyer); } } //------------------------------------------------------------------------------------------------------- } /* * Binary option smart contract------------------------------- */ contract BinaryOption { /* * binary option controled by escrow to buy NAC with good price */ // NamiCrowdSale address address public namiCrowdSaleAddr; address public escrow; // namiMultiSigWallet address public namiMultiSigWallet; Session public session; uint public timeInvestInMinute = 15; uint public timeOneSession = 20; uint public sessionId = 1; uint public rateWin = 100; uint public rateLoss = 20; uint public rateFee = 5; uint public constant MAX_INVESTOR = 20; uint public minimunEth = 10000000000000000; // minimunEth = 0.01 eth /** * Events for binany option system */ event SessionOpen(uint timeOpen, uint indexed sessionId); event InvestClose(uint timeInvestClose, uint priceOpen, uint indexed sessionId); event Invest(address indexed investor, bool choose, uint amount, uint timeInvest, uint indexed sessionId); event SessionClose(uint timeClose, uint indexed sessionId, uint priceClose, uint nacPrice, uint rateWin, uint rateLoss, uint rateFee); event Deposit(address indexed sender, uint value); /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } // there is only one session available at one timeOpen // priceOpen is price of ETH in USD // priceClose is price of ETH in USD // process of one Session // 1st: escrow reset session by run resetSession() // 2nd: escrow open session by run openSession() => save timeOpen at this time // 3rd: all investor can invest by run invest(), send minimum 0.1 ETH // 4th: escrow close invest and insert price open for this Session // 5th: escrow close session and send NAC for investor struct Session { uint priceOpen; uint priceClose; uint timeOpen; bool isReset; bool isOpen; bool investOpen; uint investorCount; mapping(uint => address) investor; mapping(uint => bool) win; mapping(uint => uint) amountInvest; } function BinaryOption(address _namiCrowdSale, address _escrow, address _namiMultiSigWallet) public { require(_namiCrowdSale != 0x0 && _escrow != 0x0); namiCrowdSaleAddr = _namiCrowdSale; escrow = _escrow; namiMultiSigWallet = _namiMultiSigWallet; } modifier onlyEscrow() { require(msg.sender==escrow); _; } modifier onlyNamiMultisig() { require(msg.sender == namiMultiSigWallet); _; } // change escrow function changeEscrow(address _escrow) public onlyNamiMultisig { require(_escrow != 0x0); escrow = _escrow; } // chagne minimunEth function changeMinEth(uint _minimunEth) public onlyEscrow { require(_minimunEth != 0); minimunEth = _minimunEth; } /// @dev Change time for investor can invest in one session, can only change at time not in session /// @param _timeInvest time invest in minutes ///---------------------------change time function------------------------------ function changeTimeInvest(uint _timeInvest) public onlyEscrow { require(!session.isOpen && _timeInvest < timeOneSession); timeInvestInMinute = _timeInvest; } function changeTimeOneSession(uint _timeOneSession) public onlyEscrow { require(!session.isOpen && _timeOneSession > timeInvestInMinute); timeOneSession = _timeOneSession; } /////------------------------change rate function------------------------------- function changeRateWin(uint _rateWin) public onlyEscrow { require(!session.isOpen); rateWin = _rateWin; } function changeRateLoss(uint _rateLoss) public onlyEscrow { require(!session.isOpen); rateLoss = _rateLoss; } function changeRateFee(uint _rateFee) public onlyEscrow { require(!session.isOpen); rateFee = _rateFee; } /// @dev withdraw ether to nami multisignature wallet, only escrow can call /// @param _amount value ether in wei to withdraw function withdrawEther(uint _amount) public onlyEscrow { require(namiMultiSigWallet != 0x0); // Available at any phase. if (this.balance > 0) { namiMultiSigWallet.transfer(_amount); } } /// @dev safe withdraw Ether to one of owner of nami multisignature wallet /// @param _withdraw address to withdraw function safeWithdraw(address _withdraw, uint _amount) public onlyEscrow { NamiMultiSigWallet namiWallet = NamiMultiSigWallet(namiMultiSigWallet); if (namiWallet.isOwner(_withdraw)) { _withdraw.transfer(_amount); } } // @dev Returns list of owners. // @return List of owner addresses. // MAX_INVESTOR = 20 function getInvestors() public view returns (address[20]) { address[20] memory listInvestor; for (uint i = 0; i < MAX_INVESTOR; i++) { listInvestor[i] = session.investor[i]; } return listInvestor; } function getChooses() public view returns (bool[20]) { bool[20] memory listChooses; for (uint i = 0; i < MAX_INVESTOR; i++) { listChooses[i] = session.win[i]; } return listChooses; } function getAmount() public view returns (uint[20]) { uint[20] memory listAmount; for (uint i = 0; i < MAX_INVESTOR; i++) { listAmount[i] = session.amountInvest[i]; } return listAmount; } /// @dev reset all data of previous session, must run before open new session // only escrow can call function resetSession() public onlyEscrow { require(!session.isReset && !session.isOpen); session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.isOpen = false; session.investOpen = false; session.investorCount = 0; for (uint i = 0; i < MAX_INVESTOR; i++) { session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } } /// @dev Open new session, only escrow can call function openSession () public onlyEscrow { require(session.isReset && !session.isOpen); session.isReset = false; // open invest session.investOpen = true; session.timeOpen = now; session.isOpen = true; SessionOpen(now, sessionId); } /// @dev Fuction for investor, minimun ether send is 0.1, one address can call one time in one session /// @param _choose choise of investor, true is call, false is put function invest (bool _choose) public payable { require(msg.value >= minimunEth && session.investOpen); // msg.value >= 0.1 ether require(now < (session.timeOpen + timeInvestInMinute * 1 minutes)); require(session.investorCount < MAX_INVESTOR); session.investor[session.investorCount] = msg.sender; session.win[session.investorCount] = _choose; session.amountInvest[session.investorCount] = msg.value; session.investorCount += 1; Invest(msg.sender, _choose, msg.value, now, sessionId); } /// @dev close invest for escrow /// @param _priceOpen price ETH in USD function closeInvest (uint _priceOpen) public onlyEscrow { require(_priceOpen != 0 && session.investOpen); require(now > (session.timeOpen + timeInvestInMinute * 1 minutes)); session.investOpen = false; session.priceOpen = _priceOpen; InvestClose(now, _priceOpen, sessionId); } /// @dev get amount of ether to buy NAC for investor /// @param _ether amount ether which investor invest /// @param _status true for investor win and false for investor loss function getEtherToBuy (uint _ether, bool _status) public view returns (uint) { if (_status) { return _ether * rateWin / 100; } else { return _ether * rateLoss / 100; } } /// @dev close session, only escrow can call /// @param _priceClose price of ETH in USD function closeSession (uint _priceClose) public onlyEscrow { require(_priceClose != 0 && now > (session.timeOpen + timeOneSession * 1 minutes)); require(!session.investOpen && session.isOpen); session.priceClose = _priceClose; bool result = (_priceClose>session.priceOpen)?true:false; uint etherToBuy; NamiCrowdSale namiContract = NamiCrowdSale(namiCrowdSaleAddr); uint price = namiContract.getPrice(); require(price != 0); for (uint i = 0; i < session.investorCount; i++) { if (session.win[i]==result) { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateWin / 100; uint etherReturn = session.amountInvest[i] - session.amountInvest[i] * rateFee / 100; (session.investor[i]).transfer(etherReturn); } else { etherToBuy = (session.amountInvest[i] - session.amountInvest[i] * rateFee / 100) * rateLoss / 100; } namiContract.buy.value(etherToBuy)(session.investor[i]); // reset investor session.investor[i] = 0x0; session.win[i] = false; session.amountInvest[i] = 0; } session.isOpen = false; SessionClose(now, sessionId, _priceClose, price, rateWin, rateLoss, rateFee); sessionId += 1; // require(!session.isReset && !session.isOpen); // reset state session session.priceOpen = 0; session.priceClose = 0; session.isReset = true; session.investOpen = false; session.investorCount = 0; } } contract PresaleToken { mapping (address => uint256) public balanceOf; function burnTokens(address _owner) public; } /* * Contract that is working with ERC223 tokens */ /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @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 _data) public returns (bool success); function tokenFallbackBuyer(address _from, uint _value, address _buyer) public returns (bool success); function tokenFallbackExchange(address _from, uint _value, uint _price) public returns (bool success); } /* * Nami Internal Exchange smartcontract----------------------------------------------------------------- * */ contract NamiExchange { using SafeMath for uint; function NamiExchange(address _namiAddress) public { NamiAddr = _namiAddress; } event UpdateBid(address owner, uint price, uint balance); event UpdateAsk(address owner, uint price, uint volume); event BuyHistory(address indexed buyer, address indexed seller, uint price, uint volume, uint time); event SellHistory(address indexed seller, address indexed buyer, uint price, uint volume, uint time); mapping(address => OrderBid) public bid; mapping(address => OrderAsk) public ask; string public name = "NacExchange"; /// address of Nami token address public NamiAddr; /// price of Nac = ETH/NAC uint public price = 1; // struct store order of user struct OrderBid { uint price; uint eth; } struct OrderAsk { uint price; uint volume; } // prevent lost ether function() payable public { require(msg.data.length != 0); require(msg.value == 0); } modifier onlyNami { require(msg.sender == NamiAddr); _; } ///////////////// //---------------------------function about bid Order----------------------------------------------------------- function placeBuyOrder(uint _price) payable public { require(_price > 0 && msg.value > 0 && bid[msg.sender].eth == 0); if (msg.value > 0) { bid[msg.sender].eth = (bid[msg.sender].eth).add(msg.value); bid[msg.sender].price = _price; UpdateBid(msg.sender, _price, bid[msg.sender].eth); } } function sellNac(uint _value, address _buyer, uint _price) public returns (bool success) { require(_price == bid[_buyer].price && _buyer != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint ethOfBuyer = bid[_buyer].eth; uint maxToken = ethOfBuyer.mul(bid[_buyer].price); require(namiToken.allowance(msg.sender, this) >= _value && _value > 0 && ethOfBuyer != 0 && _buyer != 0x0); if (_value > maxToken) { if (msg.sender.send(ethOfBuyer) && namiToken.transferFrom(msg.sender,_buyer,maxToken)) { // update order bid[_buyer].eth = 0; UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, maxToken, now); return true; } else { // revert anything revert(); } } else { uint eth = _value.div(bid[_buyer].price); if (msg.sender.send(eth) && namiToken.transferFrom(msg.sender,_buyer,_value)) { // update order bid[_buyer].eth = (bid[_buyer].eth).sub(eth); UpdateBid(_buyer, bid[_buyer].price, bid[_buyer].eth); BuyHistory(_buyer, msg.sender, bid[_buyer].price, _value, now); return true; } else { // revert anything revert(); } } } function closeBidOrder() public { require(bid[msg.sender].eth > 0 && bid[msg.sender].price > 0); // transfer ETH msg.sender.transfer(bid[msg.sender].eth); // update order bid[msg.sender].eth = 0; UpdateBid(msg.sender, bid[msg.sender].price, bid[msg.sender].eth); } //////////////// //---------------------------function about ask Order----------------------------------------------------------- // place ask order by send NAC to Nami Exchange contract // this function place sell order function tokenFallbackExchange(address _from, uint _value, uint _price) onlyNami public returns (bool success) { require(_price > 0 && _value > 0 && ask[_from].volume == 0); if (_value > 0) { ask[_from].volume = (ask[_from].volume).add(_value); ask[_from].price = _price; UpdateAsk(_from, _price, ask[_from].volume); } return true; } function closeAskOrder() public { require(ask[msg.sender].volume > 0 && ask[msg.sender].price > 0); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint previousBalances = namiToken.balanceOf(msg.sender); // transfer token namiToken.transfer(msg.sender, ask[msg.sender].volume); // update order ask[msg.sender].volume = 0; UpdateAsk(msg.sender, ask[msg.sender].price, 0); // check balance assert(previousBalances < namiToken.balanceOf(msg.sender)); } function buyNac(address _seller, uint _price) payable public returns (bool success) { require(msg.value > 0 && ask[_seller].volume > 0 && ask[_seller].price > 0); require(_price == ask[_seller].price && _seller != msg.sender); NamiCrowdSale namiToken = NamiCrowdSale(NamiAddr); uint maxEth = (ask[_seller].volume).div(ask[_seller].price); uint previousBalances = namiToken.balanceOf(msg.sender); if (msg.value > maxEth) { if (_seller.send(maxEth) && msg.sender.send(msg.value.sub(maxEth))) { // transfer token namiToken.transfer(msg.sender, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, ask[_seller].volume, now); // update order ask[_seller].volume = 0; UpdateAsk(_seller, ask[_seller].price, 0); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } else { uint nac = (msg.value).mul(ask[_seller].price); if (_seller.send(msg.value)) { // transfer token namiToken.transfer(msg.sender, nac); // update order ask[_seller].volume = (ask[_seller].volume).sub(nac); UpdateAsk(_seller, ask[_seller].price, ask[_seller].volume); SellHistory(_seller, msg.sender, ask[_seller].price, nac, now); assert(previousBalances < namiToken.balanceOf(msg.sender)); return true; } else { // revert anything revert(); } } } } contract ERC23 { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public returns (bool success); } /* * NamiMultiSigWallet smart contract------------------------------- */ /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. contract NamiMultiSigWallet { uint constant public MAX_OWNER_COUNT = 50; event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != 0); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier validRequirement(uint ownerCount, uint _required) { require(!(ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0)); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. function NamiMultiSigWallet(address[] _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i = 0; i < _owners.length; i++) { require(!(isOwner[_owners[i]] || _owners[i] == 0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) changeRequirement(owners.length); OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param owner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; OwnerRemoval(owner); OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function submitTransaction(address destination, uint value, bytes data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public notExecuted(transactionId) { if (isConfirmed(transactionId)) { // Transaction tx = transactions[transactionId]; transactions[transactionId].executed = true; // tx.executed = true; if (transactions[transactionId].destination.call.value(transactions[transactionId].value)(transactions[transactionId].data)) { Execution(transactionId); } else { ExecutionFailure(transactionId); transactions[transactionId].executed = false; } } } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public constant returns (bool) { uint count = 0; for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return Returns transaction ID. function addTransaction(address destination, uint value, bytes data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return Number of confirmations. function getConfirmationCount(uint transactionId) public constant returns (uint count) { for (uint i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; } } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public constant returns (uint count) { for (uint i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public constant returns (address[]) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return Returns array of owner addresses. function getConfirmations(uint transactionId) public constant returns (address[] _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public constant returns (uint[] _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } _transactionIds = new uint[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } } }
after month admin deposit ETH to ETH Pool
function depositEthPool(uint _roundIndex) payable public onlyEscrow { require(msg.value > 0 && round[_roundIndex].isCloseEthPool == false && round[_roundIndex].isOpen == false); if (msg.value > 0) { round[_roundIndex].ethBalance = round[_roundIndex].ethBalance.add(msg.value); Deposit(msg.sender, _roundIndex, msg.value); } }
7,873,936
pragma solidity ^0.4.18; contract Ticket { string _brand; address _owner; // constructor() public { _brand = "火车"; // msg.sender 是当前合约的创建者 _owner = msg.sender; } function setBrand(string brand) public { _brand = brand; } // 如果返回值当中有状态的变量值需要使用 constant function getBrand() constant public returns (string){ return _brand; } // 如果只是纯粹的放回一个值,例如:固定的值, function sayHello() pure public returns (string) { return "Hello World"; } // 如果当前返回的既不是固定值也不是状态变量,这个时候我们使用view function getCurrent() view public returns (address){ return msg.sender; } // 如果当前的调用者是当前的创建合约的人才可以去销毁合约 function kill() public { if (_owner == msg.sender) { selfdestruct(msg.sender); } } }
如果只是纯粹的放回一个值,例如:固定的值,
function sayHello() pure public returns (string) { return "Hello World"; }
15,786,636
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "./interfaces/IDappState.sol"; import "./DappLib.sol"; import "./interfaces/IERC1155.sol"; import "./interfaces/IERC1155Receiver.sol"; import "./interfaces/IERC1155MetadataURI.sol"; import "./imports/custom_nft/Address.sol"; import "./imports/custom_nft/Context.sol"; import "./imports/custom_nft/ERC165.sol"; import "./imports/custom_nft/generator/generator.sol"; /********************************************************************************************/ /* This contract is auto-generated based on your choices in DappStarter. You can make */ /* changes, but be aware that generating a new DappStarter project will require you to */ /* merge changes. One approach you can take is to make changes in Dapp.sol and have it */ /* call into this one. You can maintain all your data in this contract and your app logic */ /* in Dapp.sol. This lets you update and deploy Dapp.sol with revised code and still */ /* continue using this one. */ /********************************************************************************************/ contract DappState is IDappState ,Context, ERC165, IERC1155, IERC1155MetadataURI { // Allow DappLib(SafeMath) functions to be called for all uint256 types // (similar to "prototype" in Javascript) using DappLib for uint256; /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ using DappLib for DappLib.Multihash; using Address for address; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ S T A T E @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ // Account used to deploy contract address private contractOwner; /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Track authorized admins count to prevent lockout uint256 private authorizedAdminsCount = 1; // Admins authorized to manage contract mapping(address => uint256) private authorizedAdmins; /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Contracts authorized to call this one mapping(address => uint256) private authorizedContracts; /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Contract run state bool private contractRunState = true; /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ string public name; string public symbol; uint256 public decimals; // Token balance for each address mapping(address => uint256) balances; // Approval granted to transfer tokens by one address to another address mapping (address => mapping (address => uint256)) internal allowed; // Tokens currently in circulation (you'll need to update this if you create more tokens) uint256 public total; // Tokens created when contract was deployed uint256 public initialSupply; // Multiplier to convert to smallest unit uint256 public UNIT_MULTIPLIER; /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ struct IpfsDocument { // Unique identifier -- defaults to multihash digest of file bytes32 docId; bytes32 label; // Registration timestamp uint256 timestamp; // Owner of document address owner; // External Document reference DappLib.Multihash docRef; } // All added documents mapping(bytes32 => IpfsDocument) ipfsDocs; uint constant IPFS_DOCS_PAGE_SIZE = 50; uint256 public ipfsLastPage = 0; // All documents organized by page mapping(uint256 => bytes32[]) public ipfsDocsByPage; // All documents for which an account is the owner mapping(address => bytes32[]) public ipfsDocsByOwner; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private operatorApprovals; // Mapping from token ID to metadata mapping (uint256 => Generator.MetaData) public metadata; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private uri; /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ C O N S T R U C T O R @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ constructor() { contractOwner = msg.sender; /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Add account that deployed contract as an authorized admin authorizedAdmins[msg.sender] = 1; /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ name = "Achievements"; symbol = "ACVM"; decimals = 2; // Multiplier to convert to smallest unit UNIT_MULTIPLIER = 10 ** uint256(decimals); uint256 supply = 10000000; // Convert supply to smallest unit total = supply.mul(UNIT_MULTIPLIER); initialSupply = total; // Assign entire initial supply to contract owner balances[contractOwner] = total; } /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ E V E N T S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Event fired when status is changed event ChangeContractRunState ( bool indexed mode, address indexed account, uint256 timestamp ); /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Fired when an account authorizes another account to spend tokens on its behalf event Approval ( address indexed owner, address indexed spender, uint256 value ); // Fired when tokens are transferred from one account to another event Transfer ( address indexed from, address indexed to, uint256 value ); /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ // Event fired when doc is added event AddIpfsDocument ( bytes32 indexed docId, address indexed owner, uint256 timestamp ); /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ M O D I F I E R S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Modifier that requires the function caller to be a contract admin */ modifier requireContractAdmin() { require(isContractAdmin(msg.sender), "Caller is not a contract administrator"); // Modifiers require an "_" which indicates where the function body will be added _; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Modifier that requires the calling contract to be authorized */ modifier requireContractAuthorized() { require(isContractAuthorized(msg.sender), "Calling contract not authorized"); // Modifiers require an "_" which indicates where the function body will be added _; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Modifier that requires the "contractRunState" 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 requireContractRunStateActive() { require(contractRunState, "Contract is currently not active"); // Modifiers require an "_" which indicates where the function body will be added _; } /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ F U N C T I O N S @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*/ /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: ADMINISTRATOR ROLE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Checks if an account is an admin * * @param account Address of the account to check */ function isContractAdmin ( address account ) public view returns(bool) { return authorizedAdmins[account] == 1; } /** * @dev Adds a contract admin * * @param account Address of the admin to add */ function addContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdmins[account] < 1, "Account is already an administrator"); authorizedAdmins[account] = 1; authorizedAdminsCount++; } /** * @dev Removes a previously added admin * * @param account Address of the admin to remove */ function removeContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdminsCount >= 2, "Cannot remove last admin"); delete authorizedAdmins[account]; authorizedAdminsCount--; } /** * @dev Removes the last admin fully decentralizing the contract * * @param account Address of the admin to remove */ function removeLastContractAdmin ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); require(authorizedAdminsCount == 1, "Not the last admin"); delete authorizedAdmins[account]; authorizedAdminsCount--; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT ACCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Authorizes a smart contract to call this contract * * @param account Address of the calling smart contract */ function authorizeContract ( address account ) public requireContractAdmin { require(account != address(0), "Invalid address"); authorizedContracts[account] = 1; } /** * @dev Deauthorizes a previously authorized smart contract from calling this contract * * @param account Address of the calling smart contract */ function deauthorizeContract ( address account ) external requireContractAdmin { require(account != address(0), "Invalid address"); delete authorizedContracts[account]; } /** * @dev Checks if a contract is authorized to call this contract * * @param account Address of the calling smart contract */ function isContractAuthorized ( address account ) public view returns(bool) { return authorizedContracts[account] == 1; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>> ACCESS CONTROL: CONTRACT RUN STATE <<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Get active status of contract * * @return A bool that is the current active status */ function isContractRunStateActive() external view returns(bool) { return contractRunState; } /** * @dev Sets contract active status on/off * * When active status is off, all write transactions except for this one will fail */ function setContractRunState ( bool mode ) external // **** WARNING: Adding requireContractRunStateActive modifier will result in contract lockout **** requireContractAdmin // Administrator Role block is required to ensure only authorized individuals can pause contract { require(mode != contractRunState, "Run state is already set to the same value"); contractRunState = mode; emit ChangeContractRunState(mode, msg.sender, block.timestamp); } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ASSET VALUE TRACKING: TOKEN <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Total supply of tokens */ function totalSupply() external view returns (uint256) { return total; } /** * @dev Gets the balance of the calling address. * * @return An uint256 representing the amount owned by the calling address */ function balance() public view returns (uint256) { return balanceOf(msg.sender); } /** * @dev Gets the balance of the specified address. * * @param owner The address to query the balance of * @return An uint256 representing the amount owned by the passed address */ function balanceOf ( address owner ) public view returns (uint256) { return balances[owner]; } /** * @dev Transfers token for a specified address * * @param to The address to transfer to. * @param value The amount to be transferred. * @return A bool indicating if the transfer was successful. */ function transfer ( address to, uint256 value ) public returns (bool) { require(to != address(0)); require(to != msg.sender); require(value <= balanceOf(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 Transfers 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 * @return A bool indicating if the transfer was successful. */ function transferFrom ( address from, address to, uint256 value ) public returns (bool) { require(from != address(0)); require(value <= allowed[from][msg.sender]); require(value <= balanceOf(from)); require(to != address(0)); require(from != to); 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 Checks 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 Approves the passed address to spend the specified amount of tokens * on behalf of msg.sender. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A bool indicating success (always returns true) */ function approve ( address spender, uint256 value ) public returns (bool) { allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> FILE STORAGE: IPFS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/ /** * @dev Adds a new IPFS doc * * @param docId Unique identifier (multihash digest of doc) * @param label Short, descriptive label for document * @param digest Digest of folder with doc binary and metadata * @param hashFunction Function used for generating doc folder hash * @param digestLength Length of doc folder hash */ function addIpfsDocument ( bytes32 docId, bytes32 label, bytes32 digest, uint8 hashFunction, uint8 digestLength ) external { // Prevent empty string for docId require(docId[0] != 0, "Invalid docId"); // Prevent empty string for digest require(digest[0] != 0, "Invalid ipfsDoc folder digest"); // Prevent duplicate docIds require(ipfsDocs[docId].timestamp == 0, "Document already exists"); ipfsDocs[docId] = IpfsDocument({ docId: docId, label: label, timestamp: block.timestamp, owner: msg.sender, docRef: DappLib.Multihash({ digest: digest, hashFunction: hashFunction, digestLength: digestLength }) }); ipfsDocsByOwner[msg.sender].push(docId); if (ipfsDocsByPage[ipfsLastPage].length == IPFS_DOCS_PAGE_SIZE) { ipfsLastPage++; } ipfsDocsByPage[ipfsLastPage].push(docId); emit AddIpfsDocument(docId, msg.sender, ipfsDocs[docId].timestamp); } /** * @dev Gets individual IPFS doc by docId * * @param id DocumentId of doc */ function getIpfsDocument ( bytes32 id ) external view returns( bytes32 docId, bytes32 label, uint256 timestamp, address owner, bytes32 docDigest, uint8 docHashFunction, uint8 docDigestLength ) { IpfsDocument memory ipfsDoc = ipfsDocs[id]; docId = ipfsDoc.docId; label = ipfsDoc.label; timestamp = ipfsDoc.timestamp; owner = ipfsDoc.owner; docDigest = ipfsDoc.docRef.digest; docHashFunction = ipfsDoc.docRef.hashFunction; docDigestLength = ipfsDoc.docRef.digestLength; } /** * @dev Gets docs where account is/was an owner * * @param account Address of owner */ function getIpfsDocumentsByOwner ( address account ) external view returns(bytes32[] memory) { require(account != address(0), "Invalid account"); return ipfsDocsByOwner[account]; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function getURI() public view virtual override returns (string memory) { return uri; } /** @notice Transfers `amount` amount of an `id` from the `from` address to the `to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard). MUST revert if `to` is the zero address. MUST revert if balance of holder for token `id` is lower than the `amount` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param id ID of the token type @param amount Transfer amount @param data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `to` */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == msgSender() || isApprovedForAll(from, msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = msgSender(); beforeTokenTransfer(operator, from, to, asSingletonArray(id), asSingletonArray(amount), data); uint256 fromBalance = balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); balances[id][from] = fromBalance - amount; balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** @notice Transfers `amounts` amount(s) of `ids` from the `from` address to the `to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard). MUST revert if `to` is the zero address. MUST revert if length of `ids` is not the same as length of `amounts`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `ids` is lower than the respective amount(s) in `amounts` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param from Source address @param to Target address @param ids IDs of each token type (order and length must match _values array) @param amounts Transfer amounts per token type (order and length must match _ids array) @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `to` */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == msgSender() || isApprovedForAll(from, msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = msgSender(); beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); balances[id][from] = fromBalance - amount; balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** @notice Get the balance of an account's Tokens. @param account The address of the token holder @param id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return balances[id][account]; } /** @notice Get the balance of multiple account/token pairs @param accounts The addresses of the token holders @param ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param operator Address to add to the set of authorized operators @param approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address operator, bool approved) public virtual override { require(msgSender() != operator, "ERC1155: setting approval status for self"); operatorApprovals[msgSender()][operator] = approved; emit ApprovalForAll(msgSender(), operator, approved); } /** @notice Queries the approval status of an operator for a given owner. @param account The owner of the Tokens @param operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return operatorApprovals[account][operator]; } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function setURI(string memory newuri) external virtual requireContractAdmin { uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function mint(address account, uint256 id, uint256 amount, bytes memory data) public virtual requireContractAdmin { require(account != address(0), "ERC1155: mint to the zero address"); address operator = msgSender(); beforeTokenTransfer(operator, address(0), account, asSingletonArray(id), asSingletonArray(amount), data); balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } function mintNFT(address account, uint256 id, uint256 amount, Generator.MetaData memory metaData) external virtual requireContractAdmin { mint(account, id, amount, ""); metadata[id] = metaData; } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) external virtual requireContractAdmin { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = msgSender(); beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function burn(address account, uint256 id, uint256 amount) external virtual requireContractAdmin { require(account != address(0), "ERC1155: burn from the zero address"); address operator = msgSender(); beforeTokenTransfer(operator, account, address(0), asSingletonArray(id), asSingletonArray(amount), ""); uint256 accountBalance = balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); balances[id][account] = accountBalance - amount; emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) external virtual requireContractAdmin { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = msgSender(); beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 accountBalance = balances[id][account]; require(accountBalance >= amount, "ERC1155: burn amount exceeds balance"); balances[id][account] = accountBalance - amount; } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } // Example functions that demonstrate how to call into this contract that holds state from // another contract. Look in ~/interfaces/IDappState.sol for the interface definitions and // in Dapp.sol for the actual calls into this contract. /** * @dev This is an EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to READ state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function getContractOwner() external view override returns(address) { return contractOwner; } uint256 counter; // This is an example variable used only to demonstrate calling // a function that writes state from an external contract. It and // "incrementCounter" and "getCounter" functions can (should?) be deleted. /** * @dev This is an EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to WRITE state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function incrementCounter ( uint256 increment ) external override // Enable the modifier below if using the Contract Access feature // requireContractAuthorized { // NOTE: If another contract is calling this function, then msg.sender will be the address // of the calling contract and NOT the address of the user who initiated the // transaction. It is possible to get the address of the user, but this is // spoofable and therefore not recommended. require(increment > 0 && increment < 10, "Invalid increment value"); counter = counter.add(increment); // Demonstration of using SafeMath to add to a number // While verbose, using SafeMath everywhere that you // add/sub/div/mul will ensure your contract does not // have weird overflow bugs. } /** * @dev This is an another EXAMPLE function that illustrates how functions in this contract can be * called securely from another contract to READ state data. Using the Contract Access * block will enable you to make your contract more secure by restricting which external * contracts can call functions in this contract. */ function getCounter() external view override returns(uint256) { return counter; } }
a function that writes state from an external contract. It and "incrementCounter" and "getCounter" functions can (should?) be deleted. This is an EXAMPLE function that illustrates how functions in this contract can be called securely from another contract to WRITE state data. Using the Contract Access block will enable you to make your contract more secure by restricting which external contracts can call functions in this contract./ Enable the modifier below if using the Contract Access feature requireContractAuthorized NOTE: If another contract is calling this function, then msg.sender will be the address of the calling contract and NOT the address of the user who initiated the transaction. It is possible to get the address of the user, but this is spoofable and therefore not recommended. While verbose, using SafeMath everywhere that you add/sub/div/mul will ensure your contract does not have weird overflow bugs.
function incrementCounter ( uint256 increment ) external override { require(increment > 0 && increment < 10, "Invalid increment value"); }
7,214,184
./full_match/44787/0xFBf4Fa7119Ebd69c8786E628acD76FE21C3F0903/sources/contracts/ERC721/MarketV2.sol
Purchase tokens baed on the {numTokens} specified for lazy minted tokens. groupTokenId The ID of the token that's being purchased numTokens Amount of tokens to be purchased
function purchaseTokenLazy(uint256 groupTokenId, uint256 numTokens) public payable nonReentrant { address minter = _groupTokenInfoList[groupTokenId].minter; uint256 tokenPrice = _groupTokenInfoList[groupTokenId].price; uint256 maxAmount = _groupTokenInfoList[groupTokenId].amount; uint256 amountMinted = _groupTokenInfoList[groupTokenId].amountMinted; require(minter != address(0), "Market: Not a valid token"); require( minter != _msgSender(), "Market: token already owned by caller" ); require( amountMinted + numTokens <= maxAmount, "Market: Max amount of token reached" ); require( msg.value >= tokenPrice * numTokens, "Market: not enough funds" ); for (uint256 i = 0; i < numTokens; i++) { _mintToken( tokenPrice, groupTokenId + _groupTokenInfoList[groupTokenId].amountMinted + i, _groupTokenInfoList[groupTokenId].splitList, false ); } _groupTokenInfoList[groupTokenId].amountMinted = amountMinted + numTokens; _handlePayment(groupTokenId); }
13,258,726
pragma solidity 0.4.15; /// @dev The interface a contract MUST implement if it is the delegate of some (other) interface for any address other than itself. interface AIRDelegateInterface { /// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `target` or not. /// @param addr Address for which the contract will implement the interface /// @param interfaceHash sha3 hash of the name of the interface /// @return AIR_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `target`. function isDelegateFor(address addr, bytes32 interfaceHash) external constant returns(bytes32); } contract AionInterfaceRegistry { /// @notice Magic value which is returned if a contract implements an interface on behalf of some other address. bytes32 constant AIR_ACCEPT_MAGIC = sha3("AIR_ACCEPT_MAGIC"); mapping (address => mapping(bytes32 => address)) interfaces; mapping (address => address) managers; modifier canManage(address target) { require(getManager(target) == msg.sender); _; } /// @notice Indicates a contract is the `delegate` of `interfaceHash` for `target`. event InterfaceDelegateSet(address indexed target, bytes32 indexed interfaceHash, address indexed delegate); /// @notice Indicates `newManager` is the address of the new manager for `target`. event ManagerChanged(address indexed target, address indexed newManager); /// @notice Query if an address implements an interface and through which contract. /// @param target Address being queried for the delegate of an interface. /// @param interfaceHash sha3 hash of the name of the interface as a string. /// @return The address of the contract which implements the interface `interfaceHash` for `target` /// or `0x0` if `target` did not register a delegate for this interface. function getInterfaceDelegate(address target, bytes32 interfaceHash) public constant returns (address) { return interfaces[target][interfaceHash]; } /// @notice Get the manager of an address. /// @param target Address for which to return the manager. /// @return Address of the manager for a given address. function getManager(address target) public constant returns(address) { // By default the manager of an address is the same address if (managers[target] == address(0)) return target; else return managers[target]; } /// @notice Compute the sha3 hash of an interface given its name. /// @param interfaceName Name of the interface as a string. /// @return The sha3 hash of an interface name. function interfaceHash(string interfaceName) public constant returns(bytes32) { return sha3(interfaceName); } /// @notice Sets the contract which implements a specific interface for an address. /// Only the manager defined for that address can set it. /// (Each address is the manager for itself until it sets a new manager.) /// @param target Address to define the interface for. /// @param interfaceHash sha3 hash of the name of the interface as a string. function setInterfaceDelegate(address target, bytes32 interfaceHash, address delegate) public canManage(target) { if (delegate != address(0) && delegate != msg.sender) require(AIRDelegateInterface(delegate).isDelegateFor(target, interfaceHash) == AIR_ACCEPT_MAGIC); interfaces[target][interfaceHash] = delegate; InterfaceDelegateSet(target, interfaceHash, delegate); } /// @notice Sets the `manager` as manager for the `target` address. /// The new manager will be able to call `setInterfaceDelegate` for `target`. /// @param target Address for which to set the new manager. /// @param manager Address of the new manager for `target`. (Pass `0x0` to reset the manager to `target` itself.) function setManager(address target, address manager) public canManage(target) { managers[target] = manager == target ? address(0) : manager; ManagerChanged(target, manager); } }
Sets the contract which implements a specific interface for an address. Only the manager defined for that address can set it. (Each address is the manager for itself until it sets a new manager.) target Address to define the interface for. interfaceHash sha3 hash of the name of the interface as a string.
function setInterfaceDelegate(address target, bytes32 interfaceHash, address delegate) public canManage(target) { if (delegate != address(0) && delegate != msg.sender) require(AIRDelegateInterface(delegate).isDelegateFor(target, interfaceHash) == AIR_ACCEPT_MAGIC); interfaces[target][interfaceHash] = delegate; InterfaceDelegateSet(target, interfaceHash, delegate); }
1,754,349
// SPDX-License-Identifier: MIT pragma solidity >=0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import { SafeMath } from '@openzeppelin/contracts/math/SafeMath.sol'; import { IERC20 } from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import { SafeERC20 } from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import { IAction } from '../interfaces/IAction.sol'; import { ICurve } from '../interfaces/ICurve.sol'; import { IStakeDao } from '../interfaces/IStakeDao.sol'; import {ILendingPool} from "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol"; ILendingPool constant lendingPool = ILendingPool(address(0x9FE532197ad76c5a68961439604C037EB79681F0)); // Kovan import "hardhat/console.sol"; /** * Error Codes * O1: actions for the vault have not been initialized * O2: cannot execute transaction, vault is in emergency state * O3: cannot call setActions, actions have already been initialized * O4: action being set is using an invalid address * O5: action being set is a duplicated action * O6: deposited underlying (msg.value) must be greater than 0 * O7: cannot accept underlying deposit, total sdToken controlled by the vault would exceed vault cap * O8: unable to withdraw underlying, sdToken to withdraw would exceed or be equal to the current vault sdToken balance * O9: unable to withdraw underlying, underlying fee transfer to fee recipient (feeRecipient) failed * O10: unable to withdraw underlying, underlying withdrawal to user (msg.sender) failed * O11: cannot close vault positions, vault is not in locked state (VaultState.Locked) * O12: unable to rollover vault, length of allocation percentages (_allocationPercentages) passed is not equal to the initialized actions length * O13: unable to rollover vault, vault is not in unlocked state (VaultState.Unlocked) * O14: unable to rollover vault, the calculated percentage sum (sumPercentage) is greater than the base (BASE) * O15: unable to rollover vault, the calculated percentage sum (sumPercentage) is not equal to the base (BASE) * O16: withdraw reserve percentage must be less than 50% (5000) * O17: cannot call emergencyPause, vault is already in emergency state * O18: cannot call resumeFromPause, vault is not in emergency state * O19: cannot receive underlying from any address other than the curve pool address (curvePool) */ /** * @title OpynPerpVault * @author Opyn Team * @dev implementation of the Opyn Perp Vault contract that works with stakedao's underlying strategy. * Note that this implementation is meant to only specifically work for the stakedao underlying strategy and is not * a generalized contract. Stakedao's underlying strategy currently accepts curvePool LP tokens called curveLPToken from the * underlying curve pool. This strategy allows users to convert their underlying into yield earning sdToken tokens * and use the sdToken tokens as collateral to sell underlying call options on Opyn. */ contract OpynPerpVault is ERC20, ReentrancyGuard, Ownable { using SafeERC20 for IERC20; using SafeMath for uint256; enum VaultState { Emergency, Locked, Unlocked } /// @dev actions that build up this strategy (vault) address[] public actions; /// @dev address to which all fees are sent address public feeRecipient; /// @dev address of the underlying address which is earning yields address public underlying; /// @dev stakedao LP token address address public sdTokenAddress; uint256 public constant BASE = 10000; // 100% /// @dev Cap for the vault. hardcoded at 1000 for initial release uint256 public cap = 1000 ether; /// @dev withdrawal fee percentage. 50 being 0.5% uint256 public withdrawalFeePercentage = 50; /// @dev how many percentage should be reserved in vault for withdraw. 1000 being 10% uint256 public withdrawReserve = 0; /// @dev curvePool for the corresponding stakedao strategy ICurve public curvePool; /// @dev the curve LP token address for the particular pool IERC20 public curveLPToken; /// @dev the stakedao strategy contract IStakeDao stakedaoStrategy; VaultState public state; VaultState public stateBeforePause; /*===================== * Events * *====================*/ event CapUpdated(uint256 newCap); event Deposit(address account, uint256 amountDeposited, uint256 shareMinted); event Rollover(uint256[] allocations); event StateUpdated(VaultState state); event FeeSent(uint256 amount, address feeRecipient); event Withdraw(address account, uint256 amountWithdrawn, uint256 shareBurned); /*===================== * Modifiers * *====================*/ /** * @dev can only be called if actions are initialized */ function actionsInitialized() private view { require(actions.length > 0, "O1"); } /** * @dev can only be executed if vault is not in emergency state */ function notEmergency() private view { require(state != VaultState.Emergency, "O2"); } /*===================== * external function * *====================*/ constructor ( address _underlying, address _sdTokenAddress, address _curvePoolAddress, address _feeRecipient, string memory _tokenName, string memory _tokenSymbol ) ERC20(_tokenName, _tokenSymbol) { underlying = _underlying; sdTokenAddress = _sdTokenAddress; stakedaoStrategy = IStakeDao(sdTokenAddress); curveLPToken = stakedaoStrategy.token(); feeRecipient = _feeRecipient; curvePool = ICurve(_curvePoolAddress); state = VaultState.Unlocked; } function setActions(address[] memory _actions) external onlyOwner { require(actions.length == 0, "O3"); // assign actions for(uint256 i = 0 ; i < _actions.length; i++ ) { // check all items before actions[i], does not equal to action[i] require(_actions[i] != address(0), "O4"); for(uint256 j = 0; j < i; j++) { require(_actions[i] != _actions[j], "O5"); } actions.push(_actions[i]); } } /** * @notice allows owner to change the cap */ function setCap(uint256 _newCap) external onlyOwner { cap = _newCap; emit CapUpdated(_newCap); } /** * @notice total sdToken controlled by this vault */ function totalStakedaoAsset() public view returns (uint256) { uint256 debt = 0; uint256 length = actions.length; for (uint256 i = 0; i < length; i++) { debt = debt.add(IAction(actions[i]).currentValue()); } return _balance().add(debt); } /** * total underlying value of the sdToken controlled by this vault */ function totalUnderlyingControlled() external view returns (uint256) { // hard coded to 36 because crv LP token and sdToken are both 18 decimals. return totalStakedaoAsset().mul(stakedaoStrategy.getPricePerFullShare()).mul(curvePool.get_virtual_price()).div(10**36); } /** * @dev return how many sdToken you can get if you burn the number of shares, after charging the fee. */ function getWithdrawAmountByShares(uint256 _shares) external view returns (uint256) { uint256 withdrawAmount = _getWithdrawAmountByShares(_shares); return withdrawAmount.sub(_getWithdrawFee(withdrawAmount)); } /** * @notice Deposits underlying into the contract and mint vault shares. * @dev deposit into the curvePool, then into stakedao, then mint the shares to depositor, and emit the deposit event * @param amount amount of underlying to deposit *@param minCrvLPToken minimum amount of curveLPToken to get out from adding liquidity. */ //added deposits function // function deposit(uint256 amount ) external nonReentrant { // notEmergency(); // actionsInitialized(); // require(amount > 0, 'O6'); // IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); // IERC20(underlying).safeApprove(address(lendingPool), amount); // lendingPool.deposit(underlying, amount, address(this), 0); // emit Deposit(msg.sender, msg.value, amount); // } function depositUnderlying(uint256 amount ) external nonReentrant { notEmergency(); actionsInitialized(); require(amount > 0, 'O6'); IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IERC20(underlying).safeApprove(address(lendingPool), amount); lendingPool.deposit(underlying, amount, address(this), 0); emit Deposit(msg.sender, msg.value, amount); // notEmergency(); // actionsInitialized(); // require(amount > 0, 'O6'); // // the sdToken is already deposited into the contract at this point, need to substract it from total // uint256[3] memory amounts; // amounts[0] = 0; // not depositing any rebBTC // amounts[1] = amount; // amounts[2] = 0; // // deposit underlying to curvePool // IERC20 underlyingToken = IERC20(underlying); // underlyingToken.safeTransferFrom(msg.sender, address(this), amount); // underlyingToken.approve(address(curvePool), amount); // curvePool.add_liquidity(amounts, minCrvLPToken); // _depositToStakedaoAndMint(); } /** * @notice Deposits curve LP into the contract and mint vault shares. * @dev deposit into stakedao, then mint the shares to depositor, and emit the deposit event * @param amount amount of curveLP to deposit */ function depositCrvLP(uint256 amount) external nonReentrant { notEmergency(); actionsInitialized(); require(amount > 0, 'O6'); // deposit underlying to curvePool curveLPToken.safeTransferFrom(msg.sender, address(this), amount); _depositToStakedaoAndMint(); } /** * @notice Withdraws underlying from vault using vault shares * @dev burns shares, withdraws curveLPToken from stakdao, withdraws underlying from curvePool * @param _share is the number of vault shares to be burned */ function withdrawUnderlying(uint256 _share, uint256 _minUnderlying) external nonReentrant { // withdraw from curve IERC20 underlyingToken = IERC20(underlying); uint256 underlyingBalanceBefore = underlyingToken.balanceOf(address(this)); uint256 curveLPTokenBalance = _withdrawFromStakedao(_share); curvePool.remove_liquidity_one_coin(curveLPTokenBalance, 1, _minUnderlying); uint256 underlyingBalanceAfter = underlyingToken.balanceOf(address(this)); uint256 underlyingOwedToUser = underlyingBalanceAfter.sub(underlyingBalanceBefore); // send underlying to user underlyingToken.safeTransfer(msg.sender, underlyingOwedToUser); emit Withdraw(msg.sender, underlyingOwedToUser, _share); } /** * @notice Withdraws curveLPToken from stakedao * @dev burns shares, withdraws curveLPToken from stakdao * @param _share is the number of vault shares to be burned */ function withdrawCrvLp (uint256 _share) external nonReentrant { uint256 curveLPTokenBalance = _withdrawFromStakedao(_share); curveLPToken.safeTransfer(msg.sender, curveLPTokenBalance); } /** * @notice anyone can call this to close out the previous round by calling "closePositions" on all actions. * @dev iterrate through each action, close position and withdraw funds */ function closePositions() public { actionsInitialized(); require(state == VaultState.Locked, "O11"); state = VaultState.Unlocked; address cacheAddress = sdTokenAddress; address[] memory cacheActions = actions; for (uint256 i = 0; i < cacheActions.length; i = i + 1) { // 1. close position. this should revert if any position is not ready to be closed. IAction(cacheActions[i]).closePosition(); // 2. withdraw sdTokens from the action uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]); if (actionBalance > 0) IERC20(cacheAddress).safeTransferFrom(cacheActions[i], address(this), actionBalance); } emit StateUpdated(VaultState.Unlocked); } /** * @notice can only be called when the vault is unlocked. It sets the state to locked and distributes funds to each action. */ function rollOver(uint256[] calldata _allocationPercentages) external onlyOwner nonReentrant { actionsInitialized(); require(_allocationPercentages.length == actions.length, 'O12'); require(state == VaultState.Unlocked, "O13"); state = VaultState.Locked; address cacheAddress = sdTokenAddress; address[] memory cacheActions = actions; uint256 cacheBase = BASE; uint256 cacheTotalAsset = totalStakedaoAsset(); // keep track of total percentage to make sure we're summing up to 100% uint256 sumPercentage = withdrawReserve; for (uint256 i = 0; i < _allocationPercentages.length; i = i + 1) { sumPercentage = sumPercentage.add(_allocationPercentages[i]); require(sumPercentage <= cacheBase, 'O14'); uint256 newAmount = cacheTotalAsset.mul(_allocationPercentages[i]).div(cacheBase); if (newAmount > 0) IERC20(cacheAddress).safeTransfer(cacheActions[i], newAmount); IAction(cacheActions[i]).rolloverPosition(); } require(sumPercentage == cacheBase, 'O15'); emit Rollover(_allocationPercentages); emit StateUpdated(VaultState.Locked); } /** * @dev set the vault withdrawal fee recipient */ function setWithdrawalFeeRecipient(address _newWithdrawalFeeRecipient) external onlyOwner { feeRecipient = _newWithdrawalFeeRecipient; } /** * @dev set the percentage that should be reserved in vault for withdraw */ function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external onlyOwner { withdrawalFeePercentage = _newWithdrawalFeePercentage; } /** * @dev set the percentage that should be reserved in vault for withdraw */ function setWithdrawReserve(uint256 _reserve) external onlyOwner { require(_reserve < 5000, "O16"); withdrawReserve = _reserve; } /** * @dev set the state to "Emergency", which disable all withdraw and deposit */ function emergencyPause() external onlyOwner { require(state != VaultState.Emergency, "O17"); stateBeforePause = state; state = VaultState.Emergency; emit StateUpdated(VaultState.Emergency); } /** * @dev set the state from "Emergency", which disable all withdraw and deposit */ function resumeFromPause() external onlyOwner { require(state == VaultState.Emergency, "O18"); state = stateBeforePause; emit StateUpdated(stateBeforePause); } /** * @dev return how many shares you can get if you deposit {_amount} sdToken * @param _amount amount of token depositing */ function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalStakedaoAsset()); } /*===================== * Internal functions * *====================*/ function _depositToStakedaoAndMint() internal { // keep track of balance before uint256 totalSdTokenBalanceBeforeDeposit = totalStakedaoAsset(); // deposit curveLPToken to stakedao uint256 curveLPTokenToDeposit = curveLPToken.balanceOf(address(this)); curveLPToken.safeIncreaseAllowance(sdTokenAddress, curveLPTokenToDeposit); stakedaoStrategy.deposit(curveLPTokenToDeposit); // mint shares and emit event uint256 totalSdTokenWithDepositedAmount = totalStakedaoAsset(); require(totalSdTokenWithDepositedAmount < cap, 'O7'); uint256 sdTokenDeposited = totalSdTokenWithDepositedAmount.sub(totalSdTokenBalanceBeforeDeposit); uint256 share = _getSharesByDepositAmount(sdTokenDeposited, totalSdTokenBalanceBeforeDeposit); emit Deposit(msg.sender, msg.value, share); _mint(msg.sender, share); } function _withdrawFromStakedao(uint256 _share) internal returns (uint256) { notEmergency(); actionsInitialized(); uint256 currentSdTokenBalance = _balance(); uint256 sdTokenToShareOfRecipient = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(sdTokenToShareOfRecipient); uint256 sdTokenToWithdraw = sdTokenToShareOfRecipient.sub(fee); require(sdTokenToWithdraw <= currentSdTokenBalance, 'O8'); // burn shares _burn(msg.sender, _share); // withdraw from stakedao stakedaoStrategy.withdraw(sdTokenToWithdraw); // transfer fee to recipient IERC20 stakedaoToken = IERC20(sdTokenAddress); stakedaoToken.safeTransfer(feeRecipient, fee); emit FeeSent(fee, feeRecipient); return curveLPToken.balanceOf(address(this)); } /** * @dev returns remaining sdToken balance in the vault. */ function _balance() internal view returns (uint256) { return IERC20(sdTokenAddress).balanceOf(address(this)); } /** * @dev return how many shares you can get if you deposit {_amount} sdToken * @param _amount amount of token depositing * @param _totalAssetAmount amont of sdToken already in the pool before deposit */ function _getSharesByDepositAmount(uint256 _amount, uint256 _totalAssetAmount) internal view returns (uint256) { uint256 shareSupply = totalSupply(); // share amount return shareSupply == 0 ? _amount : _amount.mul(shareSupply).div(_totalAssetAmount); } /** * @dev return how many sdToken you can get if you burn the number of shares */ function _getWithdrawAmountByShares(uint256 _share) internal view returns (uint256) { // withdrawal amount return _share.mul(totalStakedaoAsset()).div(totalSupply()); } /** * @dev get amount of fee charged based on total amount of wunderlying withdrawing. */ function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) { return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE); } }
return how many shares you can get if you deposit {_amount} sdToken _amount amount of token depositing/
function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalStakedaoAsset()); }
1,843,989
./full_match/100/0x0995e02276c2c5D1712a891731998Dbb43a590fC/sources/contracts/Core.sol
Maintainer: Set `newTimestamp` as new condition `conditionId` deadline. conditionId the match or game ID newTimestamp new condition start time/
function shift(uint256 conditionId, uint64 newTimestamp) external onlyMaintainer { if (conditions[conditionId].timestamp == 0) revert ConditionNotExists(); conditions[conditionId].timestamp = newTimestamp; emit ConditionShifted(conditionId, newTimestamp); }
14,288,020
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeRouter} from "./BridgeRouter.sol"; import {IWeth} from "../../interfaces/bridge/IWeth.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; contract ETHHelper { // ============ Immutables ============ // wrapped Ether contract IWeth public immutable weth; // bridge router contract BridgeRouter public immutable bridge; // ============ Constructor ============ constructor(address _weth, address _bridge) { weth = IWeth(_weth); bridge = BridgeRouter(_bridge); IWeth(_weth).approve(_bridge, uint256(-1)); } // ============ External Functions ============ /** * @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics * identifer on the other side. * @dev As with all bridges, improper use may result in loss of funds. * @param _domain The domain to send funds to. * @param _to The 32-byte identifier of the recipient */ function sendTo(uint32 _domain, bytes32 _to) public payable { weth.deposit{value: msg.value}(); bridge.send(address(weth), msg.value, _domain, _to); } /** * @notice Sends ETH over the Optics Bridge. Sends to the same address on * the other side. * @dev WARNING: This function should only be used when sending TO an * EVM-like domain. As with all bridges, improper use may result in loss of * funds. * @param _domain The domain to send funds to */ function send(uint32 _domain) external payable { sendTo(_domain, TypeCasts.addressToBytes32(msg.sender)); } /** * @notice Sends ETH over the Optics Bridge. Sends to a specified EVM * address on the other side. * @dev This function should only be used when sending TO an EVM-like * domain. As with all bridges, improper use may result in loss of funds * @param _domain The domain to send funds to. * @param _to The EVM address of the recipient */ function sendToEVMLike(uint32 _domain, address _to) external payable { sendTo(_domain, TypeCasts.addressToBytes32(_to)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {TokenRegistry} from "./TokenRegistry.sol"; import {Router} from "../Router.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {BridgeMessage} from "./BridgeMessage.sol"; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title BridgeRouter */ contract BridgeRouter is Version0, Router, TokenRegistry { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; using SafeERC20 for IERC20; // ============ Constants ============ // 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995; uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000; // ============ Public Storage ============ // token transfer prefill ID => LP that pre-filled message to provide fast liquidity mapping(bytes32 => address) public liquidityProvider; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ======== Events ========= /** * @notice emitted when tokens are sent from this domain to another domain * @param token the address of the token contract * @param from the address sending tokens * @param toDomain the domain of the chain the tokens are being sent to * @param toId the bytes32 address of the recipient of the tokens * @param amount the amount of tokens sent */ event Send( address indexed token, address indexed from, uint32 indexed toDomain, bytes32 toId, uint256 amount ); // ======== Initializer ======== function initialize(address _tokenBeacon, address _xAppConnectionManager) public initializer { __TokenRegistry_initialize(_tokenBeacon); __XAppConnectionClient_initialize(_xAppConnectionManager); } // ======== External: Handle ========= /** * @notice Handles an incoming message * @param _origin The origin domain * @param _sender The sender address * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyRemoteRouter(_origin, _sender) { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId(); bytes29 _action = _msg.action(); // handle message based on the intended action if (_action.isTransfer()) { _handleTransfer(_tokenId, _action); } else if (_action.isDetails()) { _handleDetails(_tokenId, _action); } else if (_action.isRequestDetails()) { _handleRequestDetails(_origin, _sender, _tokenId); } else { require(false, "!valid action"); } } // ======== External: Request Token Details ========= /** * @notice Request updated token metadata from another chain * @dev This is only owner to prevent abuse and spam. Requesting details * should be done automatically on token instantiation * @param _domain The domain where that token is native * @param _id The token id on that domain */ function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner { bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); _requestDetails(_tokenId); } // ======== External: Send Token ========= /** * @notice Send tokens to a recipient on a remote chain * @param _token The token address * @param _amount The token amount * @param _destination The destination domain * @param _recipient The recipient address */ function send( address _token, uint256 _amount, uint32 _destination, bytes32 _recipient ) external { require(_amount > 0, "!amnt"); require(_recipient != bytes32(0), "!recip"); // get remote BridgeRouter address; revert if not found bytes32 _remote = _mustHaveRemote(_destination); // remove tokens from circulation on this chain IERC20 _bridgeToken = IERC20(_token); if (_isLocalOrigin(_bridgeToken)) { // if the token originates on this chain, hold the tokens in escrow // in the Router _bridgeToken.safeTransferFrom(msg.sender, address(this), _amount); } else { // if the token originates on a remote chain, burn the // representation tokens on this chain _downcast(_bridgeToken).burn(msg.sender, _amount); } // format Transfer Tokens action bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_formatTokenId(_token), _action) ); // emit Send event to record token sender emit Send( address(_bridgeToken), msg.sender, _destination, _recipient, _amount ); } // ======== External: Fast Liquidity ========= /** * @notice Allows a liquidity provider to give an * end user fast liquidity by pre-filling an * incoming transfer message. * Transfers tokens from the liquidity provider to the end recipient, minus the LP fee; * Records the liquidity provider, who receives * the full token amount when the transfer message is handled. * @dev fast liquidity can only be provided for ONE token transfer * with the same (recipient, amount) at a time. * in the case that multiple token transfers with the same (recipient, amount) * @param _message The incoming transfer message to pre-fill */ function preFill(bytes calldata _message) external { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId().mustBeTokenId(); bytes29 _action = _msg.action().mustBeTransfer(); // calculate prefill ID bytes32 _id = _preFillId(_tokenId, _action); // require that transfer has not already been pre-filled require(liquidityProvider[_id] == address(0), "!unfilled"); // record liquidity provider liquidityProvider[_id] = msg.sender; // transfer tokens from liquidity provider to token recipient IERC20 _token = _mustHaveToken(_tokenId); _token.safeTransferFrom( msg.sender, _action.evmRecipient(), _applyPreFillFee(_action.amnt()) ); } // ======== External: Custom Tokens ========= /** * @notice Enroll a custom token. This allows projects to work with * governance to specify a custom representation. * @dev This is done by inserting the custom representation into the token * lookup tables. It is permissioned to the owner (governance) and can * potentially break token representations. It must be used with extreme * caution. * After the token is inserted, new mint instructions will be sent to the * custom token. The default representation (and old custom representations) * may still be burnt. Until all users have explicitly called migrate, both * representations will continue to exist. * The custom representation MUST be trusted, and MUST allow the router to * both mint AND burn tokens at will. * @param _id the canonical ID of the Token to enroll, as a byte vector * @param _custom the address of the custom implementation to use. */ function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { // Sanity check. Ensures that human error doesn't cause an // unpermissioned contract to be enrolled. IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); // update mappings with custom token bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; } /** * @notice Migrate all tokens in a previous representation to the latest * custom representation. This works by looking up local mappings and then * burning old tokens and minting new tokens. * @dev This is explicitly opt-in to allow dapps to decide when and how to * upgrade to the new representation. * @param _oldRepr The address of the old token to migrate */ function migrate(address _oldRepr) external { // get the token ID for the old token contract TokenId memory _id = representationToCanonical[_oldRepr]; require(_id.domain != 0, "!repr"); // ensure that new token & old token are different IBridgeToken _old = IBridgeToken(_oldRepr); IBridgeToken _new = _representationForCanonical(_id); require(_new != _old, "!different"); // burn the old tokens & mint the new ones uint256 _bal = _old.balanceOf(msg.sender); _old.burn(msg.sender, _bal); _new.mint(msg.sender, _bal); } // ============ Internal: Send / UpdateDetails ============ /** * @notice Given a tokenAddress, format the tokenId * identifier for the message. * @param _token The token address * @param _tokenId The bytes-encoded tokenId */ function _formatTokenId(address _token) internal view returns (bytes29 _tokenId) { TokenId memory _tokId = _tokenIdFor(_token); _tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id); } // ============ Internal: Handle ============ /** * @notice Handles an incoming Transfer message. * * If the token is of local origin, the amount is sent from escrow. * Otherwise, a representation token is minted. * * @param _tokenId The token ID * @param _action The action */ function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal { // get the token contract for the given tokenId on this chain; // (if the token is of remote origin and there is // no existing representation token contract, the TokenRegistry will // deploy a new one) IERC20 _token = _ensureToken(_tokenId); address _recipient = _action.evmRecipient(); // If an LP has prefilled this token transfer, // send the tokens to the LP instead of the recipient bytes32 _id = _preFillId(_tokenId, _action); address _lp = liquidityProvider[_id]; if (_lp != address(0)) { _recipient = _lp; delete liquidityProvider[_id]; } // send the tokens into circulation on this chain if (_isLocalOrigin(_token)) { // if the token is of local origin, the tokens have been held in // escrow in this contract // while they have been circulating on remote chains; // transfer the tokens to the recipient _token.safeTransfer(_recipient, _action.amnt()); } else { // if the token is of remote origin, mint the tokens to the // recipient on this chain _downcast(_token).mint(_recipient, _action.amnt()); } } /** * @notice Handles an incoming Details message. * @param _tokenId The token ID * @param _action The action */ function _handleDetails(bytes29 _tokenId, bytes29 _action) internal { // get the token contract deployed on this chain // revert if no token contract exists IERC20 _token = _mustHaveToken(_tokenId); // require that the token is of remote origin // (otherwise, the BridgeRouter did not deploy the token contract, // and therefore cannot update its metadata) require(!_isLocalOrigin(_token), "!remote origin"); // update the token metadata _downcast(_token).setDetails( TypeCasts.coerceString(_action.name()), TypeCasts.coerceString(_action.symbol()), _action.decimals() ); } /** * @notice Handles an incoming RequestDetails message by sending an * UpdateDetails message to the remote chain * @dev The origin and remote are pre-checked by the handle function * `onlyRemoteRouter` modifier and can be used without additional check * @param _messageOrigin The domain from which the message arrived * @param _messageRemoteRouter The remote router that sent the message * @param _tokenId The token ID */ function _handleRequestDetails( uint32 _messageOrigin, bytes32 _messageRemoteRouter, bytes29 _tokenId ) internal { // get token & ensure is of local origin address _token = _tokenId.evmId(); require(_isLocalOrigin(_token), "!local origin"); IBridgeToken _bridgeToken = IBridgeToken(_token); // format Update Details message bytes29 _updateDetailsAction = BridgeMessage.formatDetails( TypeCasts.coerceBytes32(_bridgeToken.name()), TypeCasts.coerceBytes32(_bridgeToken.symbol()), _bridgeToken.decimals() ); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _messageOrigin, _messageRemoteRouter, BridgeMessage.formatMessage(_tokenId, _updateDetailsAction) ); } // ============ Internal: Transfer ============ function _ensureToken(bytes29 _tokenId) internal returns (IERC20) { address _local = _getTokenAddress(_tokenId); if (_local == address(0)) { // Representation does not exist yet; // deploy representation contract _local = _deployToken(_tokenId); // message the origin domain // to request the token details _requestDetails(_tokenId); } return IERC20(_local); } // ============ Internal: Request Details ============ /** * @notice Handles an incoming Details message. * @param _tokenId The token ID */ function _requestDetails(bytes29 _tokenId) internal { uint32 _destination = _tokenId.domain(); // get remote BridgeRouter address; revert if not found bytes32 _remote = remotes[_destination]; if (_remote == bytes32(0)) { return; } // format Request Details message bytes29 _action = BridgeMessage.formatRequestDetails(); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_tokenId, _action) ); } // ============ Internal: Fast Liquidity ============ /** * @notice Calculate the token amount after * taking a 5 bps (0.05%) liquidity provider fee * @param _amnt The token amount before the fee is taken * @return _amtAfterFee The token amount after the fee is taken */ function _applyPreFillFee(uint256 _amnt) internal pure returns (uint256 _amtAfterFee) { // overflow only possible if (2**256 / 9995) tokens sent once // in which case, probably not a real token _amtAfterFee = (_amnt * PRE_FILL_FEE_NUMERATOR) / PRE_FILL_FEE_DENOMINATOR; } /** * @notice get the prefillId used to identify * fast liquidity provision for incoming token send messages * @dev used to identify a token/transfer pair in the prefill LP mapping. * NOTE: This approach has a weakness: a user can receive >1 batch of tokens of * the same size, but only 1 will be eligible for fast liquidity. The * other may only be filled at regular speed. This is because the messages * will have identical `tokenId` and `action` fields. This seems fine, * tbqh. A delay of a few hours on a corner case is acceptable in v1. * @param _tokenId The token ID * @param _action The action */ function _preFillId(bytes29 _tokenId, bytes29 _action) internal view returns (bytes32) { bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.joinKeccak(_views); } /** * @dev explicit override for compiler inheritance * @dev explicit override for compiler inheritance * @return domain of chain on which the contract is deployed */ function _localDomain() internal view override(TokenRegistry, XAppConnectionClient) returns (uint32) { return XAppConnectionClient._localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IWeth { function deposit() external payable; function approve(address _who, uint256 _wad) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeMessage} from "./BridgeMessage.sol"; import {Encoding} from "./Encoding.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title TokenRegistry * @notice manages a registry of token contracts on this chain * - * We sort token types as "representation token" or "locally originating token". * Locally originating - a token contract that was originally deployed on the local chain * Representation (repr) - a token that was originally deployed on some other chain * - * When the router handles an incoming message, it determines whether the * transfer is for an asset of local origin. If not, it checks for an existing * representation contract. If no such representation exists, it deploys a new * representation contract. It then stores the relationship in the * "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always * perform a lookup in either direction * Note that locally originating tokens should NEVER be represented in these lookup tables. */ abstract contract TokenRegistry is Initializable { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; // ============ Structs ============ // Tokens are identified by a TokenId: // domain - 4 byte chain ID of the chain from which the token originates // id - 32 byte identifier of the token address on the origin chain, in that chain's address format struct TokenId { uint32 domain; bytes32 id; } // ============ Public Storage ============ // UpgradeBeacon from which new token proxies will get their implementation address public tokenBeacon; // local representation token address => token ID mapping(address => TokenId) public representationToCanonical; // hash of the tightly-packed TokenId => local representation token address // If the token is of local origin, this MUST map to address(0). mapping(bytes32 => address) public canonicalToRepresentation; // ============ Events ============ event TokenDeployed( uint32 indexed domain, bytes32 indexed id, address indexed representation ); // ======== Initializer ========= /** * @notice Initialize the TokenRegistry with UpgradeBeaconController and * XappConnectionManager. * @dev This method deploys two new contracts, and may be expensive to call. * @param _tokenBeacon The address of the upgrade beacon for bridge token * proxies */ function __TokenRegistry_initialize(address _tokenBeacon) internal initializer { tokenBeacon = _tokenBeacon; } // ======== External: Token Lookup Convenience ========= /** * @notice Looks up the canonical identifier for a local representation. * @dev If no such canonical ID is known, this instead returns (0, bytes32(0)) * @param _local The local address of the representation */ function getCanonicalAddress(address _local) external view returns (uint32 _domain, bytes32 _id) { TokenId memory _canonical = representationToCanonical[_local]; _domain = _canonical.domain; _id = _canonical.id; } /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, address _id) external view returns (address _token) { _token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id)); } // ======== Public: Token Lookup Convenience ========= /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, bytes32 _id) public view returns (address _token) { _token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id)); } // ======== Internal Functions ========= function _localDomain() internal view virtual returns (uint32); /** * @notice Get default name and details for a token * Sets name to "optics.[domain].[id]" * and symbol to * @param _tokenId the tokenId for the token */ function _defaultDetails(bytes29 _tokenId) internal pure returns (string memory _name, string memory _symbol) { // get the first and second half of the token ID (, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id())); // encode the default token name: "[decimal domain].[hex 4 bytes of ID]" _name = string( abi.encodePacked( Encoding.decimalUint32(_tokenId.domain()), // 10 ".", // 1 uint32(_secondHalfId) // 4 ) ); // allocate the memory for a new 32-byte string _symbol = new string(10 + 1 + 4); assembly { mstore(add(_symbol, 0x20), mload(add(_name, 0x20))) } } /** * @notice Deploy and initialize a new token contract * @dev Each token contract is a proxy which * points to the token upgrade beacon * @return _token the address of the token contract */ function _deployToken(bytes29 _tokenId) internal returns (address _token) { // deploy and initialize the token contract _token = address(new UpgradeBeaconProxy(tokenBeacon, "")); // initialize the token separately from the IBridgeToken(_token).initialize(); // set the default token name & symbol string memory _name; string memory _symbol; (_name, _symbol) = _defaultDetails(_tokenId); IBridgeToken(_token).setDetails(_name, _symbol, 18); // store token in mappings representationToCanonical[_token].domain = _tokenId.domain(); representationToCanonical[_token].id = _tokenId.id(); canonicalToRepresentation[_tokenId.keccak()] = _token; // emit event upon deploying new token emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token); } /** * @notice Get the local token address * for the canonical token represented by tokenID * Returns address(0) if canonical token is of remote origin * and no representation token has been deployed locally * @param _tokenId the token id of the canonical token * @return _local the local token address */ function _getTokenAddress(bytes29 _tokenId) internal view returns (address _local) { if (_tokenId.domain() == _localDomain()) { // Token is of local origin _local = _tokenId.evmId(); } else { // Token is a representation of a token of remote origin _local = canonicalToRepresentation[_tokenId.keccak()]; } } /** * @notice Return the local token contract for the * canonical tokenId; revert if there is no local token * @param _tokenId the token id of the canonical token * @return the IERC20 token contract */ function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) { address _local = _getTokenAddress(_tokenId); require(_local != address(0), "!token"); return IERC20(_local); } /** * @notice Return tokenId for a local token address * @param _token local token address (representation or canonical) * @return _id local token address (representation or canonical) */ function _tokenIdFor(address _token) internal view returns (TokenId memory _id) { _id = representationToCanonical[_token]; if (_id.domain == 0) { _id.domain = _localDomain(); _id.id = TypeCasts.addressToBytes32(_token); } } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(IERC20 _token) internal view returns (bool) { return _isLocalOrigin(address(_token)); } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(address _token) internal view returns (bool) { // If the contract WAS deployed by the TokenRegistry, // it will be stored in this mapping. // If so, it IS NOT of local origin if (representationToCanonical[_token].domain != 0) { return false; } // If the contract WAS NOT deployed by the TokenRegistry, // and the contract exists, then it IS of local origin // Return true if code exists at _addr uint256 _codeSize; // solhint-disable-next-line no-inline-assembly assembly { _codeSize := extcodesize(_token) } return _codeSize != 0; } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(bytes29 _tokenId) internal view returns (IBridgeToken) { return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]); } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(TokenId memory _tokenId) internal view returns (IBridgeToken) { return _representationForCanonical(_serializeId(_tokenId)); } /** * @notice downcast an IERC20 to an IBridgeToken * @dev Unsafe. Please know what you're doing * @param _token the IERC20 contract * @return the IBridgeToken contract */ function _downcast(IERC20 _token) internal pure returns (IBridgeToken) { return IBridgeToken(address(_token)); } /** * @notice serialize a TokenId struct into a bytes view * @param _id the tokenId * @return serialized bytes of tokenId */ function _serializeId(TokenId memory _id) internal pure returns (bytes29) { return BridgeMessage.formatTokenId(_id.domain, _id.id); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {XAppConnectionClient} from "./XAppConnectionClient.sol"; // ============ External Imports ============ import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol"; abstract contract Router is XAppConnectionClient, IMessageRecipient { // ============ Mutable Storage ============ mapping(uint32 => bytes32) public remotes; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from a remote Router contract * @param _origin The domain the message is coming from * @param _router The address the message is coming from */ modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) { require(_isRemoteRouter(_origin, _router), "!remote router"); _; } // ============ External functions ============ /** * @notice Register the address of a Router contract for the same xApp on a remote chain * @param _domain The domain of the remote xApp Router * @param _router The address of the remote xApp Router */ function enrollRemoteRouter(uint32 _domain, bytes32 _router) external onlyOwner { remotes[_domain] = _router; } // ============ Virtual functions ============ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external virtual override; // ============ Internal functions ============ /** * @notice Return true if the given domain / router is the address of a remote xApp Router * @param _domain The domain of the potential remote xApp Router * @param _router The address of the potential remote xApp Router */ function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool) { return remotes[_domain] == _router; } /** * @notice Assert that the given domain has a xApp Router registered and return its address * @param _domain The domain of the chain for which to get the xApp Router * @return _remote The address of the remote xApp Router on _domain */ function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract XAppConnectionClient is OwnableUpgradeable { // ============ Mutable Storage ============ XAppConnectionManager public xAppConnectionManager; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from an Optics Replica contract */ modifier onlyReplica() { require(_isReplica(msg.sender), "!replica"); _; } // ======== Initializer ========= function __XAppConnectionClient_initialize(address _xAppConnectionManager) internal initializer { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); __Ownable_init(); } // ============ External functions ============ /** * @notice Modify the contract the xApp uses to validate Replica contracts * @param _xAppConnectionManager The address of the xAppConnectionManager contract */ function setXAppConnectionManager(address _xAppConnectionManager) external onlyOwner { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } // ============ Internal functions ============ /** * @notice Get the local Home contract from the xAppConnectionManager * @return The local Home contract */ function _home() internal view returns (Home) { return xAppConnectionManager.home(); } /** * @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager * @return True if _potentialReplica is an enrolled Replica */ function _isReplica(address _potentialReplica) internal view returns (bool) { return xAppConnectionManager.isReplica(_potentialReplica); } /** * @notice Get the local domain from the xAppConnectionManager * @return The local domain */ function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library BridgeMessage { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; // ============ Enums ============ // WARNING: do NOT re-write the numbers / order // of message types in an upgrade; // will cause in-flight messages to be mis-interpreted enum Types { Invalid, // 0 TokenId, // 1 Message, // 2 Transfer, // 3 Details, // 4 RequestDetails // 5 } // ============ Constants ============ uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id uint256 private constant IDENTIFIER_LEN = 1; uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier // ============ Modifiers ============ /** * @notice Asserts a message is of type `_t` * @param _view The message * @param _t The expected type */ modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // ============ Internal Functions ============ /** * @notice Checks that Action is valid type * @param _action The action * @return TRUE if action is valid */ function isValidAction(bytes29 _action) internal pure returns (bool) { return isDetails(_action) || isRequestDetails(_action) || isTransfer(_action); } /** * @notice Checks that view is a valid message length * @param _view The bytes string * @return TRUE if message is valid */ function isValidMessageLength(bytes29 _view) internal pure returns (bool) { uint256 _len = _view.len(); return _len == TOKEN_ID_LEN + TRANSFER_LEN || _len == TOKEN_ID_LEN + DETAILS_LEN || _len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN; } /** * @notice Formats an action message * @param _tokenId The token ID * @param _action The action * @return The formatted message */ function formatMessage(bytes29 _tokenId, bytes29 _action) internal view typeAssert(_tokenId, Types.TokenId) returns (bytes memory) { require(isValidAction(_action), "!action"); bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.join(_views); } /** * @notice Returns the type of the message * @param _view The message * @return The type of the message */ function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /** * @notice Checks that the message is of type Transfer * @param _action The message * @return True if the message is of type Transfer */ function isTransfer(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Transfer) && messageType(_action) == Types.Transfer; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Details) && messageType(_action) == Types.Details; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isRequestDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.RequestDetails) && messageType(_action) == Types.RequestDetails; } /** * @notice Formats Transfer * @param _to The recipient address as bytes32 * @param _amnt The transfer amount * @return */ function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29) { return mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0)); } /** * @notice Formats Details * @param _name The name * @param _symbol The symbol * @param _decimals The decimals * @return The Details message */ function formatDetails( bytes32 _name, bytes32 _symbol, uint8 _decimals ) internal pure returns (bytes29) { return mustBeDetails( abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref( 0 ) ); } /** * @notice Formats Request Details * @return The Request Details message */ function formatRequestDetails() internal pure returns (bytes29) { return mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0)); } /** * @notice Formats the Token ID * @param _domain The domain * @param _id The ID * @return The formatted Token ID */ function formatTokenId(uint32 _domain, bytes32 _id) internal pure returns (bytes29) { return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0)); } /** * @notice Retrieves the domain from a TokenID * @param _tokenId The message * @return The domain */ function domain(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (uint32) { return uint32(_tokenId.indexUint(0, 4)); } /** * @notice Retrieves the ID from a TokenID * @param _tokenId The message * @return The ID */ function id(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (bytes32) { // before = 4 bytes domain return _tokenId.index(4, 32); } /** * @notice Retrieves the EVM ID * @param _tokenId The message * @return The EVM ID */ function evmId(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (address) { // before = 4 bytes domain + 12 bytes empty to trim for address return _tokenId.indexAddress(16); } /** * @notice Retrieves the action identifier from message * @param _message The action * @return The message type */ function msgType(bytes29 _message) internal pure returns (uint8) { return uint8(_message.indexUint(TOKEN_ID_LEN, 1)); } /** * @notice Retrieves the identifier from action * @param _action The action * @return The action type */ function actionType(bytes29 _action) internal pure returns (uint8) { return uint8(_action.indexUint(0, 1)); } /** * @notice Retrieves the recipient from a Transfer * @param _transferAction The message * @return The recipient address as bytes32 */ function recipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (bytes32) { // before = 1 byte identifier return _transferAction.index(1, 32); } /** * @notice Retrieves the EVM Recipient from a Transfer * @param _transferAction The message * @return The EVM Recipient */ function evmRecipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (address) { // before = 1 byte identifier + 12 bytes empty to trim for address return _transferAction.indexAddress(13); } /** * @notice Retrieves the amount from a Transfer * @param _transferAction The message * @return The amount */ function amnt(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (uint256) { // before = 1 byte identifier + 32 bytes ID return _transferAction.indexUint(33, 32); } /** * @notice Retrieves the name from Details * @param _detailsAction The message * @return The name */ function name(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier return _detailsAction.index(1, 32); } /** * @notice Retrieves the symbol from Details * @param _detailsAction The message * @return The symbol */ function symbol(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier + 32 bytes name return _detailsAction.index(33, 32); } /** * @notice Retrieves the decimals from Details * @param _detailsAction The message * @return The decimals */ function decimals(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (uint8) { // before = 1 byte identifier + 32 bytes name + 32 bytes symbol return uint8(_detailsAction.indexUint(65, 1)); } /** * @notice Retrieves the token ID from a Message * @param _message The message * @return The ID */ function tokenId(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId)); } /** * @notice Retrieves the action data from a Message * @param _message The message * @return The action */ function action(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { uint256 _actionLen = _message.len() - TOKEN_ID_LEN; uint40 _type = uint40(msgType(_message)); return _message.slice(TOKEN_ID_LEN, _actionLen, _type); } /** * @notice Converts to a Transfer * @param _action The message * @return The newly typed message */ function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == TRANSFER_LEN) { return _action.castTo(uint40(Types.Transfer)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == DETAILS_LEN) { return _action.castTo(uint40(Types.Details)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsRequestDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == REQUEST_DETAILS_LEN) { return _action.castTo(uint40(Types.RequestDetails)); } return TypedMemView.nullView(); } /** * @notice Converts to a TokenID * @param _tokenId The message * @return The newly typed message */ function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) { if (_tokenId.len() == TOKEN_ID_LEN) { return _tokenId.castTo(uint40(Types.TokenId)); } return TypedMemView.nullView(); } /** * @notice Converts to a Message * @param _message The message * @return The newly typed message */ function tryAsMessage(bytes29 _message) internal pure returns (bytes29) { if (isValidMessageLength(_message)) { return _message.castTo(uint40(Types.Message)); } return TypedMemView.nullView(); } /** * @notice Asserts that the message is of type Transfer * @param _view The message * @return The message */ function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) { return tryAsTransfer(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeRequestDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsRequestDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type TokenID * @param _view The message * @return The message */ function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) { return tryAsTokenId(_view).assertValid(); } /** * @notice Asserts that the message is of type Message * @param _view The message * @return The message */ function mustBeMessage(bytes29 _view) internal pure returns (bytes29) { return tryAsMessage(_view).assertValid(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; library Encoding { // ============ Constants ============ bytes private constant NIBBLE_LOOKUP = "0123456789abcdef"; // ============ Internal Functions ============ /** * @notice Encode a uint32 in its DECIMAL representation, with leading * zeroes. * @param _num The number to encode * @return _encoded The encoded number, suitable for use in abi. * encodePacked */ function decimalUint32(uint32 _num) internal pure returns (uint80 _encoded) { uint80 ASCII_0 = 0x30; // all over/underflows are impossible // this will ALWAYS produce 10 decimal characters for (uint8 i = 0; i < 10; i += 1) { _encoded |= ((_num % 10) + ASCII_0) << (i * 8); _num = _num / 10; } } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * @param _bytes The 32 bytes as uint256 * @return _firstHalf The top 16 bytes * @return _secondHalf The bottom 16 bytes */ function encodeHex(uint256 _bytes) internal pure returns (uint256 _firstHalf, uint256 _secondHalf) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _firstHalf |= _byteHex(_b); if (i != 16) { _firstHalf <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _secondHalf |= _byteHex(_b); if (i != 0) { _secondHalf <<= 16; } } } /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _byte The byte * @return _char The encoded hex character */ function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) { uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4 _char = uint8(NIBBLE_LOOKUP[_nibble]); } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _byte The byte * @return _encoded The hex-encoded byte */ function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) { _encoded |= _nibbleHex(_byte >> 4); // top 4 bits _encoded <<= 8; _encoded |= _nibbleHex(_byte); // lower 4 bits } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { 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()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } } // 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.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title 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; require(c / _a == _b, "Overflow during multiplication."); 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) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Remove the replica from the two-way mappings _replica replica to un-enroll/
function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); }
1,209,135
./partial_match/4/0x2F674500a367583D6Aaef312478a7cC1941a1977/sources/FECORE.sol
Returns the number of accounts that have `role`. Can be used together with {getRoleMember} to enumerate all bearers of a role./
function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); }
8,664,338
./full_match/1/0x8940fd30496bD58De8f574919f3A0382c378D842/sources/contracts/APWineAirdrop.sol
Get the next epoch start
function getNextEpochStart() external view returns (uint256) { uint256 epoch = getCurrentEpoch(); uint256 gracePeriodEnd = getGracePeriodEnd(); return epoch == 0 ? gracePeriodEnd : gracePeriodEnd.add(epochDuration.mul(epoch)); }
9,801,217
./partial_match/42/0x1e01587409a3054CE02B7A7512616BA7dCe71a51/sources/InsuranceFund.sol
withdraw token to caller _amount the amount of quoteToken caller want to withdraw/
function withdraw(Decimal.decimal calldata _amount) external override nonReentrant returns (Decimal.decimal memory badDebt) { require(beneficiary == _msgSender(), "caller is not beneficiary"); IERC20Upgradeable quoteToken = exchange.quoteAsset(); Decimal.decimal memory quoteBalance = balanceOf(quoteToken); if (_amount.toUint() > quoteBalance.toUint()) { badDebt = _amount.subD(quoteBalance); _transfer(quoteToken, _msgSender(), quoteBalance); emit Withdrawn(_msgSender(), quoteBalance.toUint(), badDebt.toUint()); _transfer(quoteToken, _msgSender(), _amount); emit Withdrawn(_msgSender(), _amount.toUint(), 0); } }
3,472,775
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../IController.sol"; import "../IConverter.sol"; import "../IHarvester.sol"; import "../IMetaVault.sol"; import "../IStrategy.sol"; import "../IVaultManager.sol"; /** * @title StrategyControllerV2 * @notice This controller allows multiple strategies to be used * for a single token, and multiple tokens are supported. */ contract StrategyControllerV2 is IController { using SafeERC20 for IERC20; using SafeMath for uint256; bool public globalInvestEnabled; uint256 public maxStrategies; IVaultManager public vaultManager; struct TokenStrategy { address[] strategies; mapping(address => uint256) index; mapping(address => bool) active; mapping(address => uint256) caps; } // token => (want => converter) mapping(address => mapping(address => address)) public converters; // token => TokenStrategy mapping(address => TokenStrategy) internal tokenStrategies; // strategy => token mapping(address => address) public override strategyTokens; // token => vault mapping(address => address) public override vaults; // vault => token mapping(address => address) public vaultTokens; /** * @notice Logged when earn is called for a strategy */ event Earn(address indexed strategy); /** * @notice Logged when harvest is called for a strategy */ event Harvest(address indexed strategy); /** * @notice Logged when insurance is claimed for a vault */ event InsuranceClaimed(address indexed vault); /** * @notice Logged when a converter is set */ event SetConverter(address input, address output, address converter); /** * @notice Logged when a vault manager is set */ event SetVaultManager(address vaultManager); /** * @notice Logged when a strategy is added for a token */ event StrategyAdded(address indexed token, address indexed strategy, uint256 cap); /** * @notice Logged when a strategy is removed for a token */ event StrategyRemoved(address indexed token, address indexed strategy); /** * @notice Logged when strategies are reordered for a token */ event StrategiesReordered( address indexed token, address indexed strategy1, address indexed strategy2 ); /** * @param _vaultManager The address of the vaultManager */ constructor(address _vaultManager) public { vaultManager = IVaultManager(_vaultManager); globalInvestEnabled = true; maxStrategies = 10; } /** * GOVERNANCE-ONLY FUNCTIONS */ /** * @notice Adds a strategy for a given token * @dev Only callable by governance * @param _token The address of the token * @param _strategy The address of the strategy * @param _cap The cap of the strategy * @param _converter The converter of the strategy (can be zero address) * @param _canHarvest Flag for whether the strategy can be harvested * @param _timeout The timeout between harvests */ function addStrategy( address _token, address _strategy, uint256 _cap, address _converter, bool _canHarvest, uint256 _timeout ) external onlyGovernance { // ensure the strategy hasn't been added require(!tokenStrategies[_token].active[_strategy], "active"); address _want = IStrategy(_strategy).want(); // ensure a converter is added if the strategy's want token is // different than the want token of the vault if (_want != IMetaVault(vaults[_token]).want()) { require(_converter != address(0), "!_converter"); converters[_token][_want] = _converter; // enable the strategy on the converter IConverter(_converter).setStrategy(_strategy, true); } // get the index of the newly added strategy uint256 index = tokenStrategies[_token].strategies.length; // ensure we haven't added too many strategies already require(index < maxStrategies, "!maxStrategies"); // push the strategy to the array of strategies tokenStrategies[_token].strategies.push(_strategy); // set the cap tokenStrategies[_token].caps[_strategy] = _cap; // set the index tokenStrategies[_token].index[_strategy] = index; // activate the strategy tokenStrategies[_token].active[_strategy] = true; // store the reverse mapping strategyTokens[_strategy] = _token; // if the strategy should be harvested if (_canHarvest) { // add it to the harvester IHarvester(vaultManager.harvester()).addStrategy(_token, _strategy, _timeout); } emit StrategyAdded(_token, _strategy, _cap); } /** * @notice Claims the insurance fund of a vault * @dev Only callable by governance * @dev When insurance is claimed by the controller, the insurance fund of * the vault is zeroed out, increasing the getPricePerFullShare and applying * the gains to everyone in the vault. * @param _vault The address of the vault */ function claimInsurance(address _vault) external onlyGovernance { IMetaVault(_vault).claimInsurance(); emit InsuranceClaimed(_vault); } /** * @notice Sets the address of the vault manager contract * @dev Only callable by governance * @param _vaultManager The address of the vault manager */ function setVaultManager(address _vaultManager) external onlyGovernance { vaultManager = IVaultManager(_vaultManager); emit SetVaultManager(_vaultManager); } /** * (GOVERNANCE|STRATEGIST)-ONLY FUNCTIONS */ /** * @notice Withdraws token from a strategy to governance * @dev Only callable by governance or the strategist * @param _strategy The address of the strategy * @param _token The address of the token */ function inCaseStrategyGetStuck( address _strategy, address _token ) external onlyStrategist { IStrategy(_strategy).withdraw(_token); IERC20(_token).safeTransfer( vaultManager.governance(), IERC20(_token).balanceOf(address(this)) ); } /** * @notice Withdraws token from the controller to governance * @dev Only callable by governance or the strategist * @param _token The address of the token * @param _amount The amount that will be withdrawn */ function inCaseTokensGetStuck( address _token, uint256 _amount ) external onlyStrategist { IERC20(_token).safeTransfer(vaultManager.governance(), _amount); } /** * @notice Removes a strategy for a given token * @dev Only callable by governance or strategist * @param _token The address of the token * @param _strategy The address of the strategy * @param _timeout The timeout between harvests */ function removeStrategy( address _token, address _strategy, uint256 _timeout ) external onlyStrategist { TokenStrategy storage tokenStrategy = tokenStrategies[_token]; // ensure the strategy is already added require(tokenStrategy.active[_strategy], "!active"); // get the index of the strategy to remove uint256 index = tokenStrategy.index[_strategy]; // get the index of the last strategy uint256 tail = tokenStrategy.strategies.length.sub(1); // get the address of the last strategy address replace = tokenStrategy.strategies[tail]; // replace the removed strategy with the tail tokenStrategy.strategies[index] = replace; // set the new index for the replaced strategy tokenStrategy.index[replace] = index; // remove the duplicate replaced strategy tokenStrategy.strategies.pop(); // remove the strategy's index delete tokenStrategy.index[_strategy]; // remove the strategy's cap delete tokenStrategy.caps[_strategy]; // deactivate the strategy delete tokenStrategy.active[_strategy]; // pull funds from the removed strategy to the vault IStrategy(_strategy).withdrawAll(); // remove the strategy from the harvester IHarvester(vaultManager.harvester()).removeStrategy(_token, _strategy, _timeout); // get the strategy want token address _want = IStrategy(_strategy).want(); // if a converter is used if (_want != IMetaVault(vaults[_token]).want()) { // disable the strategy on the converter IConverter(converters[_token][_want]).setStrategy(_strategy, false); } emit StrategyRemoved(_token, _strategy); } /** * @notice Reorders two strategies for a given token * @dev Only callable by governance or strategist * @param _token The address of the token * @param _strategy1 The address of the first strategy * @param _strategy2 The address of the second strategy */ function reorderStrategies( address _token, address _strategy1, address _strategy2 ) external onlyStrategist { require(_strategy1 != _strategy2, "_strategy1 == _strategy2"); TokenStrategy storage tokenStrategy = tokenStrategies[_token]; // ensure the strategies are already added require(tokenStrategy.active[_strategy1] && tokenStrategy.active[_strategy2], "!active"); // get the indexes of the strategies uint256 index1 = tokenStrategy.index[_strategy1]; uint256 index2 = tokenStrategy.index[_strategy2]; // set the new addresses at their indexes tokenStrategy.strategies[index1] = _strategy2; tokenStrategy.strategies[index2] = _strategy1; // update indexes tokenStrategy.index[_strategy1] = index2; tokenStrategy.index[_strategy2] = index1; emit StrategiesReordered(_token, _strategy1, _strategy2); } /** * @notice Sets/updates the cap of a strategy for a token * @dev Only callable by governance or strategist * @dev If the balance of the strategy is greater than the new cap (except if * the cap is 0), then withdraw the difference from the strategy to the vault. * @param _token The address of the token * @param _strategy The address of the strategy * @param _cap The new cap of the strategy */ function setCap( address _token, address _strategy, uint256 _cap ) external onlyStrategist { require(tokenStrategies[_token].active[_strategy], "!active"); tokenStrategies[_token].caps[_strategy] = _cap; uint256 _balance = IStrategy(_strategy).balanceOf(); // send excess funds (over cap) back to the vault if (_balance > _cap && _cap != 0) { uint256 _diff = _balance.sub(_cap); IStrategy(_strategy).withdraw(_diff); } } /** * @notice Sets/updates the converter for given input and output tokens * @dev Only callable by governance or strategist * @param _input The address of the input token * @param _output The address of the output token * @param _converter The address of the converter */ function setConverter( address _input, address _output, address _converter ) external onlyStrategist { converters[_input][_output] = _converter; emit SetConverter(_input, _output, _converter); } /** * @notice Sets/updates the global invest enabled flag * @dev Only callable by governance or strategist * @param _investEnabled The new bool of the invest enabled flag */ function setInvestEnabled(bool _investEnabled) external onlyStrategist { globalInvestEnabled = _investEnabled; } /** * @notice Sets/updates the maximum number of strategies for a token * @dev Only callable by governance or strategist * @param _maxStrategies The new value of the maximum strategies */ function setMaxStrategies(uint256 _maxStrategies) external onlyStrategist { require(_maxStrategies > 0, "!_maxStrategies"); maxStrategies = _maxStrategies; } /** * @notice Sets the address of a vault for a given token * @dev Only callable by governance or strategist * @param _token The address of the token * @param _vault The address of the vault */ function setVault(address _token, address _vault) external onlyStrategist { require(vaults[_token] == address(0), "vault"); vaults[_token] = _vault; vaultTokens[_vault] = _token; } /** * @notice Withdraws all funds from a strategy * @dev Only callable by governance or the strategist * @param _strategy The address of the strategy */ function withdrawAll(address _strategy) external onlyStrategist { // WithdrawAll sends 'want' to 'vault' IStrategy(_strategy).withdrawAll(); } /** * (GOVERNANCE|STRATEGIST|HARVESTER)-ONLY FUNCTIONS */ /** * @notice Harvests the specified strategy * @dev Only callable by governance, the strategist, or the harvester * @param _strategy The address of the strategy */ function harvestStrategy(address _strategy) external override onlyHarvester { IStrategy(_strategy).harvest(); emit Harvest(_strategy); } /** * VAULT-ONLY FUNCTIONS */ /** * @notice Invests funds into a strategy * @dev Only callable by a vault * @param _token The address of the token * @param _amount The amount that will be invested */ function earn(address _token, uint256 _amount) external override onlyVault(_token) { // get the first strategy that will accept the deposit address _strategy = getBestStrategyEarn(_token, _amount); // get the want token of the strategy address _want = IStrategy(_strategy).want(); // if the depositing token is not what the strategy wants, convert it // then transfer it to the strategy if (_want != _token) { address _converter = converters[_token][_want]; IERC20(_token).safeTransfer(_converter, _amount); _amount = IConverter(_converter).convert( _token, _want, _amount ); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } // call the strategy's deposit function IStrategy(_strategy).deposit(); emit Earn(_strategy); } /** * @notice Withdraws funds from a strategy * @dev Only callable by a vault * @dev If the withdraw amount is greater than the first strategy given * by getBestStrategyWithdraw, this function will loop over strategies * until the requested amount is met. * @param _token The address of the token * @param _amount The amount that will be withdrawn */ function withdraw(address _token, uint256 _amount) external override onlyVault(_token) { ( address[] memory _strategies, uint256[] memory _amounts ) = getBestStrategyWithdraw(_token, _amount); for (uint i = 0; i < _strategies.length; i++) { // getBestStrategyWithdraw will return arrays larger than needed // if this happens, simply exit the loop if (_strategies[i] == address(0)) { break; } IStrategy(_strategies[i]).withdraw(_amounts[i]); } } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns the balance of the sum of all strategies for a given token * @dev This function would make deposits more expensive for the more strategies * that are added for a given token * @param _token The address of the token */ function balanceOf(address _token) external view override returns (uint256 _balance) { uint256 k = tokenStrategies[_token].strategies.length; for (uint i = 0; i < k; i++) { IStrategy _strategy = IStrategy(tokenStrategies[_token].strategies[i]); address _want = _strategy.want(); if (_want != _token) { address _converter = converters[_token][_want]; _balance = _balance.add(IConverter(_converter).convert_rate( _want, _token, _strategy.balanceOf() )); } else { _balance = _balance.add(_strategy.balanceOf()); } } } /** * @notice Returns the cap of a strategy for a given token * @param _token The address of the token * @param _strategy The address of the strategy */ function getCap(address _token, address _strategy) external view returns (uint256) { return tokenStrategies[_token].caps[_strategy]; } /** * @notice Returns whether investing is enabled for the calling vault * @dev Should be called by the vault */ function investEnabled() external view override returns (bool) { if (globalInvestEnabled) { return tokenStrategies[vaultTokens[msg.sender]].strategies.length > 0; } return false; } /** * @notice Returns all the strategies for a given token * @param _token The address of the token */ function strategies(address _token) external view returns (address[] memory) { return tokenStrategies[_token].strategies; } /** * @notice Returns the want address of a given token * @dev Since strategies can have different want tokens, default to using the * want token of the vault for a given token. * @param _token The address of the token */ function want(address _token) external view override returns (address) { return IMetaVault(vaults[_token]).want(); } /** * @notice Returns the fee for withdrawing a specified amount * @param _amount The amount that will be withdrawn */ function withdrawFee( address, uint256 _amount ) external view override returns (uint256 _fee) { return vaultManager.withdrawalProtectionFee().mul(_amount).div(10000); } /** * PUBLIC VIEW FUNCTIONS */ /** * @notice Returns the best (optimistic) strategy for funds to be sent to with earn * @param _token The address of the token * @param _amount The amount that will be invested */ function getBestStrategyEarn( address _token, uint256 _amount ) public view returns (address _strategy) { // get the index of the last strategy uint256 k = tokenStrategies[_token].strategies.length; // scan backwards from the index to the beginning of strategies for (uint i = k; i > 0; i--) { _strategy = tokenStrategies[_token].strategies[i - 1]; // get the new balance if the _amount were added to the strategy uint256 balance = IStrategy(_strategy).balanceOf().add(_amount); uint256 cap = tokenStrategies[_token].caps[_strategy]; // stop scanning if the deposit wouldn't go over the cap if (balance <= cap || cap == 0) { break; } } // if never broken from the loop, use the last scanned strategy // this could cause it to go over cap if (for some reason) no strategies // were added with 0 cap } /** * @notice Returns the best (optimistic) strategy for funds to be withdrawn from * @dev Since Solidity doesn't support dynamic arrays in memory, the returned arrays * from this function will always be the same length as the amount of strategies for * a token. Check that _strategies[i] != address(0) when consuming to know when to * break out of the loop. * @param _token The address of the token * @param _amount The amount that will be withdrawn */ function getBestStrategyWithdraw( address _token, uint256 _amount ) public view returns ( address[] memory _strategies, uint256[] memory _amounts ) { // get the length of strategies uint256 k = tokenStrategies[_token].strategies.length; // initialize fixed-length memory arrays _strategies = new address[](k); _amounts = new uint256[](k); // scan forward from the the beginning of strategies for (uint i = 0; i < k; i++) { address _strategy = tokenStrategies[_token].strategies[i]; _strategies[i] = _strategy; // get the balance of the strategy uint256 _balance = IStrategy(_strategy).balanceOf(); // if the strategy doesn't have the balance to cover the withdraw if (_balance < _amount) { // withdraw what we can and add to the _amounts _amounts[i] = _balance; _amount = _amount.sub(_balance); } else { // stop scanning if the balance is more than the withdraw amount _amounts[i] = _amount; break; } } } /** * MODIFIERS */ modifier onlyGovernance() { require(msg.sender == vaultManager.governance(), "!governance"); _; } modifier onlyStrategist() { require(msg.sender == vaultManager.strategist() || msg.sender == vaultManager.governance(), "!strategist" ); _; } modifier onlyHarvester() { require( msg.sender == vaultManager.harvester() || msg.sender == vaultManager.strategist() || msg.sender == vaultManager.governance(), "!harvester" ); _; } modifier onlyVault(address _token) { require(msg.sender == vaults[_token], "!vault"); _; } }
Returns the best (optimistic) strategy for funds to be withdrawn from Since Solidity doesn't support dynamic arrays in memory, the returned arrays from this function will always be the same length as the amount of strategies for a token. Check that _strategies[i] != address(0) when consuming to know when to break out of the loop. _token The address of the token _amount The amount that will be withdrawn/ get the length of strategies initialize fixed-length memory arrays scan forward from the the beginning of strategies get the balance of the strategy if the strategy doesn't have the balance to cover the withdraw withdraw what we can and add to the _amounts stop scanning if the balance is more than the withdraw amount
function getBestStrategyWithdraw( address _token, uint256 _amount ) public view returns ( address[] memory _strategies, uint256[] memory _amounts ) { uint256 k = tokenStrategies[_token].strategies.length; _strategies = new address[](k); _amounts = new uint256[](k); for (uint i = 0; i < k; i++) { address _strategy = tokenStrategies[_token].strategies[i]; _strategies[i] = _strategy; uint256 _balance = IStrategy(_strategy).balanceOf(); if (_balance < _amount) { _amounts[i] = _balance; _amount = _amount.sub(_balance); _amounts[i] = _amount; break; } } }
5,471,945
./partial_match/1/0xD3faD4C5e4D24646F90A0c8876314b17243E9460/sources/contracts/KounPass.sol
Set the state machine mint phase Use restricted to contract owner _mintPhase New mint phase, 0 = INACTIVE / 1 = ALLOWLIST_MINT / 2 = PUBLIC_MINT / 3 = SOLD_OUT/
function setMintPhase(MintPhase _mintPhase) external onlyOwner { mintPhase = _mintPhase; }
2,677,009
./partial_match/1/0x5F0B23Ba4Dcb8e0Bb5d81ceE1dB2de2B13E264a1/sources/InDefiEcoPreMining.sol
dfTokenizedStrategy.burnTokens(amount, 0, 0, flashloanFromAddress);
function withdrawToken(IToken token, uint256 amount, address receiver) internal { if (receiver != address(this)) { if (token.universalBalanceOf(address(this)) >= amount) { token.universalTransfer(receiver, amount); return; } } if (address(token) == DAI_ADDRESS) { dfTokenizedStrategy.burnTokens(amount, true); dfTokenizedStrategy.burnTokens(0, 0, amount, flashloanFromAddress); dfTokenizedStrategy.burnTokens(0, amount, 0, flashloanFromAddress); require(false); } if (receiver != address(this)) token.universalTransfer(receiver, amount); }
3,596,391
// File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: REMIX_FILE_SYNC/ApprovedCreatorRegistryInterface.sol pragma solidity ^0.4.22; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract ApprovedCreatorRegistryInterface { function getVersion() public pure returns (uint); function typeOfContract() public pure returns (string); function isOperatorApprovedForCustodialAccount( address _operator, address _custodialAddress) public view returns (bool); } // File: REMIX_FILE_SYNC/DigitalMediaStoreInterface.sol pragma solidity 0.4.25; /** * Interface to the digital media store external contract that is * responsible for storing the common digital media and collection data. * This allows for new token contracts to be deployed and continue to reference * the digital media and collection data. */ contract DigitalMediaStoreInterface { function getDigitalMediaStoreVersion() public pure returns (uint); function getStartingDigitalMediaId() public view returns (uint256); function registerTokenContractAddress() external; /** * Creates a new digital media object in storage * @param _creator address the address of the creator * @param _printIndex uint32 the current print index for the limited edition media * @param _totalSupply uint32 the total allowable prints for this media * @param _collectionId uint256 the collection id that this media belongs to * @param _metadataPath string the ipfs metadata path * @return the id of the new digital media created */ function createDigitalMedia( address _creator, uint32 _printIndex, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external returns (uint); /** * Increments the current print index of the digital media object * @param _digitalMediaId uint256 the id of the digital media * @param _increment uint32 the amount to increment by */ function incrementDigitalMediaPrintIndex( uint256 _digitalMediaId, uint32 _increment) external; /** * Retrieves the digital media object by id * @param _digitalMediaId uint256 the address of the creator */ function getDigitalMedia(uint256 _digitalMediaId) external view returns( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath); /** * Creates a new collection * @param _creator address the address of the creator * @param _metadataPath string the ipfs metadata path * @return the id of the new collection created */ function createCollection(address _creator, string _metadataPath) external returns (uint); /** * Retrieves a collection by id * @param _collectionId uint256 */ function getCollection(uint256 _collectionId) external view returns( uint256 id, address creator, string metadataPath); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/ownership/Ownable.sol pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/lifecycle/Pausable.sol pragma solidity ^0.4.21; /** * @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: REMIX_FILE_SYNC/MediaStoreVersionControl.sol pragma solidity 0.4.25; /** * A special control class that is used to configure and manage a token contract's * different digital media store versions. * * Older versions of token contracts had the ability to increment the digital media's * print edition in the media store, which was necessary in the early stages to provide * upgradeability and flexibility. * * New verions will get rid of this ability now that token contract logic * is more stable and we've built in burn capabilities. * * In order to support the older tokens, we need to be able to look up the appropriate digital * media store associated with a given digital media id on the latest token contract. */ contract MediaStoreVersionControl is Pausable { // The single allowed creator for this digital media contract. DigitalMediaStoreInterface public v1DigitalMediaStore; // The current digitial media store, used for this tokens creation. DigitalMediaStoreInterface public currentDigitalMediaStore; uint256 public currentStartingDigitalMediaId; /** * Validates that the managers are initialized. */ modifier managersInitialized() { require(v1DigitalMediaStore != address(0)); require(currentDigitalMediaStore != address(0)); _; } /** * Sets a digital media store address upon construction. * Once set it's immutable, so that a token contract is always * tied to one digital media store. */ function setDigitalMediaStoreAddress(address _dmsAddress) internal { DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 2, "Incorrect version."); currentDigitalMediaStore = candidateDigitalMediaStore; currentDigitalMediaStore.registerTokenContractAddress(); currentStartingDigitalMediaId = currentDigitalMediaStore.getStartingDigitalMediaId(); } /** * Publicly callable by the owner, but can only be set one time, so don't make * a mistake when setting it. * * Will also check that the version on the other end of the contract is in fact correct. */ function setV1DigitalMediaStoreAddress(address _dmsAddress) public onlyOwner { require(address(v1DigitalMediaStore) == 0, "V1 media store already set."); DigitalMediaStoreInterface candidateDigitalMediaStore = DigitalMediaStoreInterface(_dmsAddress); require(candidateDigitalMediaStore.getDigitalMediaStoreVersion() == 1, "Incorrect version."); v1DigitalMediaStore = candidateDigitalMediaStore; v1DigitalMediaStore.registerTokenContractAddress(); } /** * Depending on the digital media id, determines whether to return the previous * version of the digital media manager. */ function _getDigitalMediaStore(uint256 _digitalMediaId) internal view managersInitialized returns (DigitalMediaStoreInterface) { if (_digitalMediaId < currentStartingDigitalMediaId) { return v1DigitalMediaStore; } else { return currentDigitalMediaStore; } } } // File: REMIX_FILE_SYNC/DigitalMediaManager.sol pragma solidity 0.4.25; /** * Manager that interfaces with the underlying digital media store contract. */ contract DigitalMediaManager is MediaStoreVersionControl { struct DigitalMedia { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string metadataPath; } struct DigitalMediaCollection { uint256 id; address creator; string metadataPath; } ApprovedCreatorRegistryInterface public creatorRegistryStore; // Set the creator registry address upon construction. Immutable. function setCreatorRegistryStore(address _crsAddress) internal { ApprovedCreatorRegistryInterface candidateCreatorRegistryStore = ApprovedCreatorRegistryInterface(_crsAddress); require(candidateCreatorRegistryStore.getVersion() == 1); // Simple check to make sure we are adding the registry contract indeed // https://fravoll.github.io/solidity-patterns/string_equality_comparison.html require(keccak256(candidateCreatorRegistryStore.typeOfContract()) == keccak256("approvedCreatorRegistry")); creatorRegistryStore = candidateCreatorRegistryStore; } /** * Validates that the Registered store is initialized. */ modifier registryInitialized() { require(creatorRegistryStore != address(0)); _; } /** * Retrieves a collection object by id. */ function _getCollection(uint256 _id) internal view managersInitialized returns(DigitalMediaCollection) { uint256 id; address creator; string memory metadataPath; (id, creator, metadataPath) = currentDigitalMediaStore.getCollection(_id); DigitalMediaCollection memory collection = DigitalMediaCollection({ id: id, creator: creator, metadataPath: metadataPath }); return collection; } /** * Retrieves a digital media object by id. */ function _getDigitalMedia(uint256 _id) internal view managersInitialized returns(DigitalMedia) { uint256 id; uint32 totalSupply; uint32 printIndex; uint256 collectionId; address creator; string memory metadataPath; DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_id); (id, totalSupply, printIndex, collectionId, creator, metadataPath) = _digitalMediaStore.getDigitalMedia(_id); DigitalMedia memory digitalMedia = DigitalMedia({ id: id, creator: creator, totalSupply: totalSupply, printIndex: printIndex, collectionId: collectionId, metadataPath: metadataPath }); return digitalMedia; } /** * Increments the print index of a digital media object by some increment. */ function _incrementDigitalMediaPrintIndex(DigitalMedia _dm, uint32 _increment) internal managersInitialized { DigitalMediaStoreInterface _digitalMediaStore = _getDigitalMediaStore(_dm.id); _digitalMediaStore.incrementDigitalMediaPrintIndex(_dm.id, _increment); } // Check if the token operator is approved for the owner address function isOperatorApprovedForCustodialAccount( address _operator, address _owner) internal view registryInitialized returns(bool) { return creatorRegistryStore.isOperatorApprovedForCustodialAccount( _operator, _owner); } } // File: REMIX_FILE_SYNC/SingleCreatorControl.sol pragma solidity 0.4.25; /** * A special control class that's used to help enforce that a DigitalMedia contract * will service only a single creator's address. This is used when deploying a * custom token contract owned and managed by a single creator. */ contract SingleCreatorControl { // The single allowed creator for this digital media contract. address public singleCreatorAddress; // The single creator has changed. event SingleCreatorChanged( address indexed previousCreatorAddress, address indexed newCreatorAddress); /** * Sets the single creator associated with this contract. This function * can only ever be called once, and should ideally be called at the point * of constructing the smart contract. */ function setSingleCreator(address _singleCreatorAddress) internal { require(singleCreatorAddress == address(0), "Single creator address already set."); singleCreatorAddress = _singleCreatorAddress; } /** * Checks whether a given creator address matches the single creator address. * Will always return true if a single creator address was never set. */ function isAllowedSingleCreator(address _creatorAddress) internal view returns (bool) { require(_creatorAddress != address(0), "0x0 creator addresses are not allowed."); return singleCreatorAddress == address(0) || singleCreatorAddress == _creatorAddress; } /** * A publicly accessible function that allows the current single creator * assigned to this contract to change to another address. */ function changeSingleCreator(address _newCreatorAddress) public { require(_newCreatorAddress != address(0)); require(msg.sender == singleCreatorAddress, "Not approved to change single creator."); singleCreatorAddress = _newCreatorAddress; emit SingleCreatorChanged(singleCreatorAddress, _newCreatorAddress); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _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; } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.4.21; /** * @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() public view returns (string _name); function symbol() public 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 { } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol pragma solidity ^0.4.21; /** * @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,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @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. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.21; /** * 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. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol pragma solidity ^0.4.21; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: REMIX_FILE_SYNC/ERC721Safe.sol pragma solidity 0.4.25; // We have to specify what version of compiler this code will compile with contract ERC721Safe is ERC721Token { bytes4 constant internal InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant internal InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('safeTransferFrom(address,address,uint256)')); function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // File: REMIX_FILE_SYNC/Memory.sol pragma solidity 0.4.25; library Memory { // Size of a word, in bytes. uint internal constant WORD_SIZE = 32; // Size of the header of a 'bytes' array. uint internal constant BYTES_HEADER_SIZE = 32; // Address of the free memory pointer. uint internal constant FREE_MEM_PTR = 0x40; // Compares the 'len' bytes starting at address 'addr' in memory with the 'len' // bytes starting at 'addr2'. // Returns 'true' if the bytes are the same, otherwise 'false'. function equals(uint addr, uint addr2, uint len) internal pure returns (bool equal) { assembly { equal := eq(keccak256(addr, len), keccak256(addr2, len)) } } // Compares the 'len' bytes starting at address 'addr' in memory with the bytes stored in // 'bts'. It is allowed to set 'len' to a lower value then 'bts.length', in which case only // the first 'len' bytes will be compared. // Requires that 'bts.length >= len' function equals(uint addr, uint len, bytes memory bts) internal pure returns (bool equal) { require(bts.length >= len); uint addr2; assembly { addr2 := add(bts, /*BYTES_HEADER_SIZE*/32) } return equals(addr, addr2, len); } // Allocates 'numBytes' bytes in memory. This will prevent the Solidity compiler // from using this area of memory. It will also initialize the area by setting // each byte to '0'. function allocate(uint numBytes) internal pure returns (uint addr) { // Take the current value of the free memory pointer, and update. assembly { addr := mload(/*FREE_MEM_PTR*/0x40) mstore(/*FREE_MEM_PTR*/0x40, add(addr, numBytes)) } uint words = (numBytes + WORD_SIZE - 1) / WORD_SIZE; for (uint i = 0; i < words; i++) { assembly { mstore(add(addr, mul(i, /*WORD_SIZE*/32)), 0) } } } // Copy 'len' bytes from memory address 'src', to address 'dest'. // This function does not check the or destination, it only copies // the bytes. function copy(uint src, uint dest, uint len) internal pure { // Copy word-length chunks while possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } dest += WORD_SIZE; src += WORD_SIZE; } // Copy remaining bytes uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } // Returns a memory pointer to the provided bytes array. function ptr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := bts } } // Returns a memory pointer to the data portion of the provided bytes array. function dataPtr(bytes memory bts) internal pure returns (uint addr) { assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // This function does the same as 'dataPtr(bytes memory)', but will also return the // length of the provided bytes array. function fromBytes(bytes memory bts) internal pure returns (uint addr, uint len) { len = bts.length; assembly { addr := add(bts, /*BYTES_HEADER_SIZE*/32) } } // Creates a 'bytes memory' variable from the memory address 'addr', with the // length 'len'. The function will allocate new memory for the bytes array, and // the 'len bytes starting at 'addr' will be copied into that new memory. function toBytes(uint addr, uint len) internal pure returns (bytes memory bts) { bts = new bytes(len); uint btsptr; assembly { btsptr := add(bts, /*BYTES_HEADER_SIZE*/32) } copy(addr, btsptr, len); } // Get the word stored at memory address 'addr' as a 'uint'. function toUint(uint addr) internal pure returns (uint n) { assembly { n := mload(addr) } } // Get the word stored at memory address 'addr' as a 'bytes32'. function toBytes32(uint addr) internal pure returns (bytes32 bts) { assembly { bts := mload(addr) } } /* // Get the byte stored at memory address 'addr' as a 'byte'. function toByte(uint addr, uint8 index) internal pure returns (byte b) { require(index < WORD_SIZE); uint8 n; assembly { n := byte(index, mload(addr)) } b = byte(n); } */ } // File: REMIX_FILE_SYNC/HelperUtils.sol pragma solidity 0.4.25; /** * Internal helper functions */ contract HelperUtils { // converts bytes32 to a string // enable this when you use it. Saving gas for now // function bytes32ToString(bytes32 x) private pure returns (string) { // bytes memory bytesString = new bytes(32); // uint charCount = 0; // for (uint j = 0; j < 32; j++) { // byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); // if (char != 0) { // bytesString[charCount] = char; // charCount++; // } // } // bytes memory bytesStringTrimmed = new bytes(charCount); // for (j = 0; j < charCount; j++) { // bytesStringTrimmed[j] = bytesString[j]; // } // return string(bytesStringTrimmed); // } /** * Concatenates two strings * @param _a string * @param _b string * @return string concatenation of two string */ function strConcat(string _a, string _b) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } } // File: REMIX_FILE_SYNC/DigitalMediaToken.sol pragma solidity 0.4.25; /** * The DigitalMediaToken contract. Fully implements the ERC721 contract * from OpenZeppelin without any modifications to it. * * This contract allows for the creation of: * 1. New Collections * 2. New DigitalMedia objects * 3. New DigitalMediaRelease objects * * The primary piece of logic is to ensure that an ERC721 token can * have a supply and print edition that is enforced by this contract. */ contract DigitalMediaToken is DigitalMediaManager, ERC721Safe, HelperUtils, SingleCreatorControl { event DigitalMediaReleaseCreateEvent( uint256 id, address owner, uint32 printEdition, string tokenURI, uint256 digitalMediaId); // Event fired when a new digital media is created event DigitalMediaCreateEvent( uint256 id, address storeContractAddress, address creator, uint32 totalSupply, uint32 printIndex, uint256 collectionId, string metadataPath); // Event fired when a digital media's collection is event DigitalMediaCollectionCreateEvent( uint256 id, address storeContractAddress, address creator, string metadataPath); // Event fired when a digital media is burned event DigitalMediaBurnEvent( uint256 id, address caller, address storeContractAddress); // Event fired when burning a token event DigitalMediaReleaseBurnEvent( uint256 tokenId, address owner); event UpdateDigitalMediaPrintIndexEvent( uint256 digitalMediaId, uint32 printEdition); // Event fired when a creator assigns a new creator address. event ChangedCreator( address creator, address newCreator); struct DigitalMediaRelease { // The unique edition number of this digital media release uint32 printEdition; // Reference ID to the digital media metadata uint256 digitalMediaId; } // Maps internal ERC721 token ID to digital media release object. mapping (uint256 => DigitalMediaRelease) public tokenIdToDigitalMediaRelease; // Maps a creator address to a new creator address. Useful if a creator // changes their address or the previous address gets compromised. mapping (address => address) public approvedCreators; // Token ID counter uint256 internal tokenIdCounter = 0; constructor (string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter) public ERC721Token(_tokenName, _tokenSymbol) { tokenIdCounter = _tokenIdStartingCounter; } /** * Creates a new digital media object. * @param _creator address the creator of this digital media * @param _totalSupply uint32 the total supply a creation could have * @param _collectionId uint256 the collectionId that it belongs to * @param _metadataPath string the path to the ipfs metadata * @return uint the new digital media id */ function _createDigitalMedia( address _creator, uint32 _totalSupply, uint256 _collectionId, string _metadataPath) internal returns (uint) { require(_validateCollection(_collectionId, _creator), "Creator for collection not approved."); uint256 newDigitalMediaId = currentDigitalMediaStore.createDigitalMedia( _creator, 0, _totalSupply, _collectionId, _metadataPath); emit DigitalMediaCreateEvent( newDigitalMediaId, address(currentDigitalMediaStore), _creator, _totalSupply, 0, _collectionId, _metadataPath); return newDigitalMediaId; } /** * Burns a token for a given tokenId and caller. * @param _tokenId the id of the token to burn. * @param _caller the address of the caller. */ function _burnToken(uint256 _tokenId, address _caller) internal { address owner = ownerOf(_tokenId); require(_caller == owner || getApproved(_tokenId) == _caller || isApprovedForAll(owner, _caller), "Failed token burn. Caller is not approved."); _burn(owner, _tokenId); delete tokenIdToDigitalMediaRelease[_tokenId]; emit DigitalMediaReleaseBurnEvent(_tokenId, owner); } /** * Burns a digital media. Once this function succeeds, this digital media * will no longer be able to mint any more tokens. Existing tokens need to be * burned individually though. * @param _digitalMediaId the id of the digital media to burn * @param _caller the address of the caller. */ function _burnDigitalMedia(uint256 _digitalMediaId, address _caller) internal { DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); require(_checkApprovedCreator(_digitalMedia.creator, _caller) || isApprovedForAll(_digitalMedia.creator, _caller), "Failed digital media burn. Caller not approved."); uint32 increment = _digitalMedia.totalSupply - _digitalMedia.printIndex; _incrementDigitalMediaPrintIndex(_digitalMedia, increment); address _burnDigitalMediaStoreAddress = address(_getDigitalMediaStore(_digitalMedia.id)); emit DigitalMediaBurnEvent( _digitalMediaId, _caller, _burnDigitalMediaStoreAddress); } /** * Creates a new collection * @param _creator address the creator of this collection * @param _metadataPath string the path to the collection ipfs metadata * @return uint the new collection id */ function _createCollection( address _creator, string _metadataPath) internal returns (uint) { uint256 newCollectionId = currentDigitalMediaStore.createCollection( _creator, _metadataPath); emit DigitalMediaCollectionCreateEvent( newCollectionId, address(currentDigitalMediaStore), _creator, _metadataPath); return newCollectionId; } /** * Creates _count number of new digital media releases (i.e a token). * Bumps up the print index by _count. * @param _owner address the owner of the digital media object * @param _digitalMediaId uint256 the digital media id */ function _createDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _count) internal { require(_count > 0, "Failed print edition. Creation count must be > 0."); require(_count < 10000, "Cannot print more than 10K tokens at once"); DigitalMedia memory _digitalMedia = _getDigitalMedia(_digitalMediaId); uint32 currentPrintIndex = _digitalMedia.printIndex; require(_checkApprovedCreator(_digitalMedia.creator, _owner), "Creator not approved."); require(isAllowedSingleCreator(_owner), "Creator must match single creator address."); require(_count + currentPrintIndex <= _digitalMedia.totalSupply, "Total supply exceeded."); string memory tokenURI = HelperUtils.strConcat("ipfs://ipfs/", _digitalMedia.metadataPath); for (uint32 i=0; i < _count; i++) { uint32 newPrintEdition = currentPrintIndex + 1 + i; DigitalMediaRelease memory _digitalMediaRelease = DigitalMediaRelease({ printEdition: newPrintEdition, digitalMediaId: _digitalMediaId }); uint256 newDigitalMediaReleaseId = _getNextTokenId(); tokenIdToDigitalMediaRelease[newDigitalMediaReleaseId] = _digitalMediaRelease; emit DigitalMediaReleaseCreateEvent( newDigitalMediaReleaseId, _owner, newPrintEdition, tokenURI, _digitalMediaId ); // This will assign ownership and also emit the Transfer event as per ERC721 _mint(_owner, newDigitalMediaReleaseId); _setTokenURI(newDigitalMediaReleaseId, tokenURI); tokenIdCounter = tokenIdCounter.add(1); } _incrementDigitalMediaPrintIndex(_digitalMedia, _count); emit UpdateDigitalMediaPrintIndexEvent(_digitalMediaId, currentPrintIndex + _count); } /** * Checks that a given caller is an approved creator and is allowed to mint or burn * tokens. If the creator was changed it will check against the updated creator. * @param _caller the calling address * @return bool allowed or not */ function _checkApprovedCreator(address _creator, address _caller) internal view returns (bool) { address approvedCreator = approvedCreators[_creator]; if (approvedCreator != address(0)) { return approvedCreator == _caller; } else { return _creator == _caller; } } /** * Validates the an address is allowed to create a digital media on a * given collection. Collections are tied to addresses. */ function _validateCollection(uint256 _collectionId, address _address) private view returns (bool) { if (_collectionId == 0 ) { return true; } DigitalMediaCollection memory collection = _getCollection(_collectionId); return _checkApprovedCreator(collection.creator, _address); } /** * Generates a new token id. */ function _getNextTokenId() private view returns (uint256) { return tokenIdCounter.add(1); } /** * Changes the creator that is approved to printing new tokens and creations. * Either the _caller must be the _creator or the _caller must be the existing * approvedCreator. * @param _caller the address of the caller * @param _creator the address of the current creator * @param _newCreator the address of the new approved creator */ function _changeCreator(address _caller, address _creator, address _newCreator) internal { address approvedCreator = approvedCreators[_creator]; require(_caller != address(0) && _creator != address(0), "Creator must be valid non 0x0 address."); require(_caller == _creator || _caller == approvedCreator, "Unauthorized caller."); if (approvedCreator == address(0)) { approvedCreators[_caller] = _newCreator; } else { require(_caller == approvedCreator, "Unauthorized caller."); approvedCreators[_creator] = _newCreator; } emit ChangedCreator(_creator, _newCreator); } /** * Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). */ function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } } // File: REMIX_FILE_SYNC/OBOControl.sol pragma solidity 0.4.25; contract OBOControl is Pausable { // List of approved on behalf of users. mapping (address => bool) public approvedOBOs; /** * Add a new approved on behalf of user address. */ function addApprovedOBO(address _oboAddress) external onlyOwner { approvedOBOs[_oboAddress] = true; } /** * Removes an approved on bhealf of user address. */ function removeApprovedOBO(address _oboAddress) external onlyOwner { delete approvedOBOs[_oboAddress]; } /** * @dev Modifier to make the obo calls only callable by approved addressess */ modifier isApprovedOBO() { require(approvedOBOs[msg.sender] == true); _; } } // File: REMIX_FILE_SYNC/WithdrawFundsControl.sol pragma solidity 0.4.25; contract WithdrawFundsControl is Pausable { // List of approved on withdraw addresses mapping (address => uint256) public approvedWithdrawAddresses; // Full day wait period before an approved withdraw address becomes active uint256 constant internal withdrawApprovalWaitPeriod = 60 * 60 * 24; event WithdrawAddressAdded(address withdrawAddress); event WithdrawAddressRemoved(address widthdrawAddress); /** * Add a new approved on behalf of user address. */ function addApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { approvedWithdrawAddresses[_withdrawAddress] = now; emit WithdrawAddressAdded(_withdrawAddress); } /** * Removes an approved on bhealf of user address. */ function removeApprovedWithdrawAddress(address _withdrawAddress) external onlyOwner { delete approvedWithdrawAddresses[_withdrawAddress]; emit WithdrawAddressRemoved(_withdrawAddress); } /** * Checks that a given withdraw address ia approved and is past it's required * wait time. */ function isApprovedWithdrawAddress(address _withdrawAddress) internal view returns (bool) { uint256 approvalTime = approvedWithdrawAddresses[_withdrawAddress]; require (approvalTime > 0); return now - approvalTime > withdrawApprovalWaitPeriod; } } // File: REMIX_FILE_SYNC/openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol pragma solidity ^0.4.21; contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } // File: REMIX_FILE_SYNC/DigitalMediaSaleBase.sol pragma solidity 0.4.25; /** * Base class that manages the underlying functions of a Digital Media Sale, * most importantly the escrow of digital tokens. * * Manages ensuring that only approved addresses interact with this contract. * */ contract DigitalMediaSaleBase is ERC721Holder, Pausable, OBOControl, WithdrawFundsControl { using SafeMath for uint256; // Mapping of token contract address to bool indicated approval. mapping (address => bool) public approvedTokenContracts; /** * Adds a new token contract address to be approved to be called. */ function addApprovedTokenContract(address _tokenContractAddress) public onlyOwner { approvedTokenContracts[_tokenContractAddress] = true; } /** * Remove an approved token contract address from the list of approved addresses. */ function removeApprovedTokenContract(address _tokenContractAddress) public onlyOwner { delete approvedTokenContracts[_tokenContractAddress]; } /** * Checks that a particular token contract address is a valid address. */ function _isValidTokenContract(address _tokenContractAddress) internal view returns (bool) { return approvedTokenContracts[_tokenContractAddress]; } /** * Returns an ERC721 instance of a token contract address. Throws otherwise. * Only valid and approved token contracts are allowed to be interacted with. */ function _getTokenContract(address _tokenContractAddress) internal view returns (ERC721Safe) { require(_isValidTokenContract(_tokenContractAddress)); return ERC721Safe(_tokenContractAddress); } /** * Checks with the ERC-721 token contract that the _claimant actually owns the token. */ function _owns(address _claimant, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.ownerOf(_tokenId) == _claimant); } /** * Checks with the ERC-721 token contract the owner of the a token */ function _ownerOf(uint256 _tokenId, address _tokenContractAddress) internal view returns (address) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return tokenContract.ownerOf(_tokenId); } /** * Checks to ensure that the token owner has approved the escrow contract */ function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.isApprovedForAll(_seller, this) || tokenContract.getApproved(_tokenId) == address(this)); } /** * Escrows an ERC-721 token from the seller to this contract. Assumes that the escrow contract * is already approved to make the transfer, otherwise it will fail. */ function _escrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(_seller, this, _tokenId); } /** * Transfer an ERC-721 token from escrow to the buyer. This is to be called after a purchase is * completed. */ function _transfer(address _receiver, uint256 _tokenId, address _tokenContractAddress) internal { // it will throw if transfer fails ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); tokenContract.safeTransferFrom(this, _receiver, _tokenId); } /** * Method to check whether this is an escrow contract */ function isEscrowContract() public pure returns(bool) { return true; } /** * Withdraws all the funds to a specified non-zero address */ function withdrawFunds(address _withdrawAddress) public onlyOwner { require(isApprovedWithdrawAddress(_withdrawAddress)); _withdrawAddress.transfer(address(this).balance); } } // File: REMIX_FILE_SYNC/DigitalMediaCore.sol pragma solidity 0.4.25; /** * This is the main driver contract that is used to control and run the service. Funds * are managed through this function, underlying contracts are also updated through * this contract. * * This class also exposes a set of creation methods that are allowed to be created * by an approved token creator, on behalf of a particular address. This is meant * to simply the creation flow for MakersToken users that aren't familiar with * the blockchain. The ERC721 tokens that are created are still fully compliant, * although it is possible for a malicious token creator to mint unwanted tokens * on behalf of a creator. Worst case, the creator can burn those tokens. */ contract DigitalMediaCore is DigitalMediaToken { using SafeMath for uint32; // List of approved token creators (on behalf of the owner) mapping (address => bool) public approvedTokenCreators; // Mapping from owner to operator accounts. mapping (address => mapping (address => bool)) internal oboOperatorApprovals; // Mapping of all disabled OBO operators. mapping (address => bool) public disabledOboOperators; // OboApproveAll Event event OboApprovalForAll( address _owner, address _operator, bool _approved); // Fired when disbaling obo capability. event OboDisabledForAll(address _operator); constructor ( string _tokenName, string _tokenSymbol, uint256 _tokenIdStartingCounter, address _dmsAddress, address _crsAddress) public DigitalMediaToken( _tokenName, _tokenSymbol, _tokenIdStartingCounter) { paused = true; setDigitalMediaStoreAddress(_dmsAddress); setCreatorRegistryStore(_crsAddress); } /** * Retrieves a Digital Media object. */ function getDigitalMedia(uint256 _id) external view returns ( uint256 id, uint32 totalSupply, uint32 printIndex, uint256 collectionId, address creator, string metadataPath) { DigitalMedia memory digitalMedia = _getDigitalMedia(_id); require(digitalMedia.creator != address(0), "DigitalMedia not found."); id = _id; totalSupply = digitalMedia.totalSupply; printIndex = digitalMedia.printIndex; collectionId = digitalMedia.collectionId; creator = digitalMedia.creator; metadataPath = digitalMedia.metadataPath; } /** * Retrieves a collection. */ function getCollection(uint256 _id) external view returns ( uint256 id, address creator, string metadataPath) { DigitalMediaCollection memory digitalMediaCollection = _getCollection(_id); require(digitalMediaCollection.creator != address(0), "Collection not found."); id = _id; creator = digitalMediaCollection.creator; metadataPath = digitalMediaCollection.metadataPath; } /** * Retrieves a Digital Media Release (i.e a token) */ function getDigitalMediaRelease(uint256 _id) external view returns ( uint256 id, uint32 printEdition, uint256 digitalMediaId) { require(exists(_id)); DigitalMediaRelease storage digitalMediaRelease = tokenIdToDigitalMediaRelease[_id]; id = _id; printEdition = digitalMediaRelease.printEdition; digitalMediaId = digitalMediaRelease.digitalMediaId; } /** * Creates a new collection. * * No creations of any kind are allowed when the contract is paused. */ function createCollection(string _metadataPath) external whenNotPaused { _createCollection(msg.sender, _metadataPath); } /** * Creates a new digital media object. */ function createDigitalMedia(uint32 _totalSupply, uint256 _collectionId, string _metadataPath) external whenNotPaused { _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); } /** * Creates a new digital media object and mints it's first digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleases( uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused { uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaAndReleasesInNewCollection( uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused { uint256 collectionId = _createCollection(msg.sender, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(msg.sender, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(msg.sender, digitalMediaId, _numReleases); } /** * Creates a new digital media release (token) for a given digital media id. * * No creations of any kind are allowed when the contract is paused. */ function createDigitalMediaReleases(uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused { _createDigitalMediaReleases(msg.sender, _digitalMediaId, _numReleases); } /** * Deletes a token / digital media release. Doesn't modify the current print index * and total to be printed. Although dangerous, the owner of a token should always * be able to burn a token they own. * * Only the owner of the token or accounts approved by the owner can burn this token. */ function burnToken(uint256 _tokenId) external { _burnToken(_tokenId, msg.sender); } /* Support ERC721 burn method */ function burn(uint256 tokenId) public { _burnToken(tokenId, msg.sender); } /** * Ends the production run of a digital media. Afterwards no more tokens * will be allowed to be printed for this digital media. Used when a creator * makes a mistake and wishes to burn and recreate their digital media. * * When a contract is paused we do not allow new tokens to be created, * so stopping the production of a token doesn't have much purpose. */ function burnDigitalMedia(uint256 _digitalMediaId) external whenNotPaused { _burnDigitalMedia(_digitalMediaId, msg.sender); } /** * Resets the approval rights for a given tokenId. */ function resetApproval(uint256 _tokenId) external { clearApproval(msg.sender, _tokenId); } /** * Changes the creator for the current sender, in the event we * need to be able to mint new tokens from an existing digital media * print production. When changing creator, the old creator will * no longer be able to mint tokens. * * A creator may need to be changed: * 1. If we want to allow a creator to take control over their token minting (i.e go decentralized) * 2. If we want to re-issue private keys due to a compromise. For this reason, we can call this function * when the contract is paused. * @param _creator the creator address * @param _newCreator the new creator address */ function changeCreator(address _creator, address _newCreator) external { _changeCreator(msg.sender, _creator, _newCreator); } /**********************************************************************/ /**Calls that are allowed to be called by approved creator addresses **/ /**********************************************************************/ /** * Add a new approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function addApprovedTokenCreator(address _creatorAddress) external onlyOwner { require(disabledOboOperators[_creatorAddress] != true, "Address disabled."); approvedTokenCreators[_creatorAddress] = true; } /** * Removes an approved token creator. * * Only the owner of this contract can update approved Obo accounts. */ function removeApprovedTokenCreator(address _creatorAddress) external onlyOwner { delete approvedTokenCreators[_creatorAddress]; } /** * @dev Modifier to make the approved creation calls only callable by approved token creators */ modifier isApprovedCreator() { require( (approvedTokenCreators[msg.sender] == true && disabledOboOperators[msg.sender] != true), "Unapproved OBO address."); _; } /** * Only the owner address can set a special obo approval list. * When issuing OBO management accounts, we should give approvals through * this method only so that we can very easily reset it's approval in * the event of a disaster scenario. * * Only the owner themselves is allowed to give OboApproveAll access. */ function setOboApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender, "Approval address is same as approver."); require(approvedTokenCreators[_to], "Unrecognized OBO address."); require(disabledOboOperators[_to] != true, "Approval address is disabled."); oboOperatorApprovals[msg.sender][_to] = _approved; emit OboApprovalForAll(msg.sender, _to, _approved); } /** * Only called in a disaster scenario if the account has been compromised. * There's no turning back from this and the oboAddress will no longer be * able to be given approval rights or perform obo functions. * * Only the owner of this contract is allowed to disable an Obo address. * */ function disableOboAddress(address _oboAddress) public onlyOwner { require(approvedTokenCreators[_oboAddress], "Unrecognized OBO address."); disabledOboOperators[_oboAddress] = true; delete approvedTokenCreators[_oboAddress]; emit OboDisabledForAll(_oboAddress); } /** * Override the isApprovalForAll to check for a special oboApproval list. Reason for this * is that we can can easily remove obo operators if they every become compromised. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { if (disabledOboOperators[_operator] == true) { return false; } else if (isOperatorApprovedForCustodialAccount(_operator, _owner) == true) { return true; } else if (oboOperatorApprovals[_owner][_operator]) { return true; } else { return super.isApprovedForAll(_owner, _operator); } } /** * Creates a new digital media object and mints it's digital media release tokens. * Called on behalf of the _owner. Pass count to mint `n` number of tokens. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleases( address _owner, uint32 _totalSupply, uint256 _collectionId, string _metadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, _collectionId, _metadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates a new collection, a new digital media object within it and mints a new * digital media release token. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaAndReleasesInNewCollection( address _owner, uint32 _totalSupply, string _digitalMediaMetadataPath, string _collectionMetadataPath, uint32 _numReleases) external whenNotPaused isApprovedCreator { uint256 collectionId = _createCollection(_owner, _collectionMetadataPath); uint256 digitalMediaId = _createDigitalMedia(_owner, _totalSupply, collectionId, _digitalMediaMetadataPath); _createDigitalMediaReleases(_owner, digitalMediaId, _numReleases); } /** * Creates multiple digital media releases (tokens) for a given digital media id. * Called on behalf of the _owner. * * Only approved creators are allowed to create Obo. * * No creations of any kind are allowed when the contract is paused. */ function oboCreateDigitalMediaReleases( address _owner, uint256 _digitalMediaId, uint32 _numReleases) external whenNotPaused isApprovedCreator { _createDigitalMediaReleases(_owner, _digitalMediaId, _numReleases); } }
Checks to ensure that the token owner has approved the escrow contract/
function _approvedForEscrow(address _seller, uint256 _tokenId, address _tokenContractAddress) internal view returns (bool) { ERC721Safe tokenContract = _getTokenContract(_tokenContractAddress); return (tokenContract.isApprovedForAll(_seller, this) || tokenContract.getApproved(_tokenId) == address(this)); }
890,416
pragma solidity >=0.4.22 <0.6.0; pragma experimental ABIEncoderV2; import "./RoleManager.sol"; import "./TokenManager.sol"; //This contracts handles the trip logic and acts as a platform contract owning the TokenManager contract and the RoleManager contract contract PlatformContract { offer[] tripArray; //each trip offer by a lessor is stored in this array uint256[] indexOfID; //0 means offer got deleted RoleManager roleManager; //roleManager contract associated to this platform contract TokenManager tokenManager; //tokenManager contract associated to this platform contract mapping (address => user) public usermap; //can rent or subrent objects //Verifier Section //calling neccessary modifiers to implement the trip logic from the subclass //Every role issue not directly related to trips is exclusively handeled in the subclass modifier onlyVerifiedRenter(uint8 objectType) { require (roleManager.isVerifiedRenter(msg.sender, objectType) == true); _; } //objectType descirbes the sharing object category (car, charging station, bike, ...) modifier onlyVerifiedLessor(uint8 objectType) { require (roleManager.isVerifiedLessor(msg.sender, objectType) == true); _; } modifier onlyVerifiers() { require (roleManager.isVerifier(msg.sender) == true); _; } //renters who fail to pay for a trip have limited action right on the paltform modifier onlyWithoutDebt() { require (tokenManager.hasDebt(msg.sender) == 0); _; } modifier onlyAuthorities() { require (roleManager.isAuthority(msg.sender) == true); _; } //renters or lessors which violated laws or acted in a malicious way can be blocked by authorities modifier isNotBlockedRenter() { require (roleManager.isBlocked(msg.sender, false) == false); _; } modifier isNotBlockedLessor() { require (roleManager.isBlocked(msg.sender, true) == false); _; } //Each offer issued by a verified lessor needs to provide the following attributes struct offer //offer cant be reserved while its started { address lessor; //lessor of the rental object uint256 startTime; //start time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt uint256 endTime; //end time in sconds since uint epoch (01.January 1970) -> use DateTime contract to convert Date to timestampt uint64 latpickupLocation; //lattitude of rental object pcikup location uint64 longpickupLocation; //longitude of rental object pcikup location uint64[10] latPolygons; uint64[10] longPolygons; // at most 10 lattitude and longitude points to define return area of rental object address renter; //renter of the object bool reserved; //Is a trip reserved? uint256 reservedBlockNumber; //BlockNumber when a trip got reserved uint256 maxReservedAmount; //max amount of reservation time allowed in blocknumbers bool readyToUse; //Lessor needs to state if the device is ready for use (unlockable, ...) so that the renter does not need to pay for waiting //bool locked; //user might want to lock the object (car,..) during a trip to unlock it later (maybe not needed to be handled on chain but rather by interacting with the device itself) uint256 started; //Block number of start time, 0 by default -> acts as a bool check uint256 userDemandsEnd; //Block number of end demand uint256 id; //Uid of the trip uint256 price; //price in tokens per block (5 secs) uint8 objectType; //car, charging station, ... string model; //further information like BMW i3, Emmy Vesper, can be also used to present a more accurate picture to the user in the app } //users can be lessors or renters struct user { bool reserved; //did the user reserve a trip? -> maybe increase to a limit of multiple trips(?) bool started; //did the user start a trip? uint256 rating; //Review Rating for that user from 1-5 on Client side -> possible future feature that lessors can also rate renters and trips may automatically reject low rated renters uint256 ratingCount; //how often has this user been rated? Used to calculate rating mapping(address => bool) hasRatingRight; //checks if user has the right to give a 1-5 star rating for a trip lessor (1 right for each ended trip) mapping(address => bool) hasReportRight; //checks if the user has the right to give a report for a trip lessor } //description: how do you want to name the first token? constructor(string memory description) public { roleManager = new RoleManager(msg.sender); //creating a new instance of a subcontract in the parent class //Initializes first authority when contract is created tokenManager = new TokenManager(); tokenManager.createNewToken(msg.sender,description); //Genesis Token/ First Token offer memory temp; //Genesis offer, cant be booked tripArray.push(temp); indexOfID.push(0); //0 id, indicates that trip got deleted, never used for an existing trip, points to Genesis trip } //authorities who want to interact with the On Chain Governance need the address of the created local instance of the RoleManager contract function getRoleManagerAddress() public view returns(address) { return address(roleManager); } function getTokemManagerAddress() public view returns(address) { return address(tokenManager); } //after an authority is voted in it has the right to create at most one token for itself function createNewToken(string memory description) public onlyAuthorities { tokenManager.createNewToken(msg.sender, description); } //ReservationSection //Checks if object can be reservated by anyone right now, true is it can get reservated function getIsReservable(uint256 id) public view returns (bool) { if(tripArray[indexOfID[id]].reserved == false) //Even when the users status gets changed from reserved to started after starting a trip, the trip status actually is reserved and started at the same time return true; if(block.number - tripArray[indexOfID[id]].reservedBlockNumber > tripArray[indexOfID[id]].maxReservedAmount && tripArray[indexOfID[id]].started == 0) //if a trip exceeds the maxReservedAmount but was not started yet it can be reserved by another party again return true; return false; } //Object needs to be free, user needs to be verifired and cant have other reservations function reserveTrip(uint256 id) public onlyVerifiedRenter( tripArray[indexOfID[id]].objectType) onlyWithoutDebt isNotBlockedRenter { require(usermap[msg.sender].reserved == false); //***************else: emit already reserved Trip event*************** require(getIsReservable(id) == true); //***************else: emit already reserved by somone else event *************** // require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //with 5secs blocktime around 4 mins worth of balance usermap[msg.sender].reserved = true; tripArray[indexOfID[id]].reserved = true; tripArray[indexOfID[id]].renter = msg.sender; tripArray[indexOfID[id]].reservedBlockNumber = block.number; //reservation gets timstampt as its validity is time limited //***************emit Reservation successful event*************** // tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //give allowance instead? } //canceling trip is only possible if user reserved the trip but did not start it yet function cancelReserve(uint256 id) public { if(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0) { tripArray[indexOfID[id]].reserved = false; usermap[msg.sender].reserved = false; //***************emit Reservation cancel successful event*************** // tokenManager.unblockOtherPaymentsOfUser(msg.sender); } //***************emit Reservation cancel not successful event*************** } //start and end Trip section //users can only start trips if they are not blocked, dont have any debt, have a minimum balancethreshold right now, have not started another trip yet, have given the tokenManager contract allowance to deduct tokens on their behalf function startTrip(uint256 id) public onlyWithoutDebt isNotBlockedRenter { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started == 0); require(usermap[msg.sender].started == false); //user can only have 1 started trip // require(usermap[msg.sender].balance > 1000); //require minimum balance *************change ERC20***************** require(tokenManager.getTotalBalanceOfUser(msg.sender) > 50*tripArray[indexOfID[id]].price); //user should have atleast enough balance for 50*5seconds -> around 4mins, minimum trip length require(tokenManager.getHasTotalAllowance(msg.sender) == true); //emit tripStart(tripAddress, tripKey, msg.sender, block.number); tokenManager.blockOtherPaymentsOfUser(msg.sender, tripArray[indexOfID[id]].lessor); //user gets blocked to make transactions to other addresses tripArray[indexOfID[id]].readyToUse = false; //setting unlocked to false to esnure rental object is ready to use before user is charged tripArray[indexOfID[id]].started = block.number; usermap[msg.sender].started = true; usermap[msg.sender].hasReportRight[tripArray[indexOfID[id]].lessor] = true; //renter gets the right to submit a report if something is wrong at the start or during the trip (e.g. object not found, object not functioning properly, lessor maliciously rejected end of trip), reports always have to be accompanied by off chain prove client side and will be reviewed by authorites (or possibly additional roles) } //Authority needs to confirm after start trip that device is ready to used (unlocked,...) function confirmReadyToUse(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender); tripArray[indexOfID[id]].started = block.number; //update started so user does not pay for waiting time tripArray[indexOfID[id]].readyToUse = true; //emit unlocked event } //only callable by Renter, demanding End of trip has to be confrimed by the lessor (valid drop off location,...) function demandEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(tripArray[indexOfID[id]].userDemandsEnd == 0); tripArray[indexOfID[id]].userDemandsEnd = block.number; } //only callable by Renter, if lessor does not respond within 15 seconds, the renter can force end the trip function userForcesEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].renter == msg.sender && tripArray[indexOfID[id]].started != 0); require(usermap[msg.sender].started == true); //safety check, shouldnt be neccessarry to check require(block.number > tripArray[indexOfID[id]].userDemandsEnd+3); //authority has 3 blocks time to answer to endDemand request contractEndsTrip(id); } //only callable by lessor if user wants to end the trip, confirms that the pbject was returned adequatly function confirmEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); require(tripArray[indexOfID[id]].userDemandsEnd != 0); contractEndsTrip(id); } //only callable by lessor if user wants to end the trip, states that the pbject was returned inadequatly, rejects endTrip attempt of renter, renter can always report against malicious use of this function function rejectEndTrip(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); require(tripArray[indexOfID[id]].userDemandsEnd != 0); tripArray[indexOfID[id]].userDemandsEnd = 0; tripArray[indexOfID[id]].userDemandsEnd = 0; //probably best to add an event and parse a string reason in parameters to state and explain why trip end was rejected } //On long rentals Lessor can call this function to ensure sufficient balance from the user -> maybe dont use that function, just tell the user and add debt -> good idea for charging station as renter can force end easily here function doubtBalanceEnd(uint256 id) public { require(tripArray[indexOfID[id]].lessor == msg.sender && tripArray[indexOfID[id]].started != 0); //**************ERC20*********** if balance is not sufficient, renter can end contract require(tripArray[indexOfID[id]].objectType == 4); //assuming object type 4 means charging station, function only makes sense for charging station require(tokenManager.getTotalBalanceOfUser(msg.sender) > 10*tripArray[indexOfID[id]].price); //if user has less than 50seconds worth of balance then the Lessor can forceEnd the trip to prevent failure of payment contractEndsTrip(id); //Alternative: automatically end trips after certain amount and require user to rebook trips } //if renter demands end of trip and forces it or lessor confirms, the PlatformContract calls this function to handle payment and set all trip and user states to the right value again function contractEndsTrip (uint256 id) internal { //*****************************ERC20Payment, out of money(?)************************************** if(tripArray[indexOfID[id]].readyToUse) //user only needs to pay if the device actually responded and is ready to use -> maybe take out for testing to not require vehicle response all the time { if( tripArray[indexOfID[id]].userDemandsEnd == 0) //in this case user has to pay the difference form the current block number, should only happen if trip was force ended by authority tokenManager.handlePayment(block.number - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,´price of trip, from and to address else //in this case user only has to be the time until he/she demanded end of trip (user does not have to pay for the time it takes the rental object authority to confirm the trip) tokenManager.handlePayment(tripArray[indexOfID[id]].userDemandsEnd - tripArray[indexOfID[id]].started,tripArray[indexOfID[id]].price, msg.sender, tripArray[indexOfID[id]].lessor); //handle payment with elapsed time,´price of trip, from and to address } if(tokenManager.hasDebt(msg.sender) == 0) tokenManager.unblockOtherPaymentsOfUser(msg.sender); //only unblocks user if the user managed to pay the full amount usermap[msg.sender].started = false; usermap[msg.sender].hasRatingRight[tripArray[indexOfID[id]].lessor] = true; //address def; tripArray[indexOfID[id]].renter = address(0); //-> prob adress(0) tripArray[indexOfID[id]].reserved = false; tripArray[indexOfID[id]].started = 0; tripArray[indexOfID[id]].userDemandsEnd = 0; tripArray[indexOfID[id]].readyToUse = false; //restrict user from access to the vehicle => needs to be replicated in device logic } //returns the maxiumum amount of blocks the user can still rent the device before he/she runs out of balance, useful for client side warnings function getMaxRamainingTime(uint256 id) public view returns (uint256) { require(tripArray[indexOfID[id]].started != 0); uint256 currentPrice = (block.number - tripArray[indexOfID[id]].started)*tripArray[indexOfID[id]].price; uint256 userBalance = tokenManager.getTotalBalanceOfUser(tripArray[indexOfID[id]].renter); uint256 theoreticalBalanceLeft = currentPrice -userBalance; return theoreticalBalanceLeft/tripArray[indexOfID[id]].price; } //User has a rating right for each ended trip function rateTrip(address LessorAddress, uint8 rating) public { require(usermap[msg.sender].hasRatingRight[LessorAddress] == true); require(rating > 0); require(rating < 6); usermap[LessorAddress].rating += rating; usermap[LessorAddress].ratingCount++; usermap[msg.sender].hasRatingRight[LessorAddress] = false; } //User has the right to report a lessor for each started trip (might be useful to also add one for each reserved trip but allows spamming) function reportLessor(address LessorAddress, uint8 rating, string memory message) public { require(usermap[msg.sender].hasReportRight[LessorAddress] == true); //****here reports could be stored in an array with an own report governance logic or emited as an event for offchain handling by auhtorities which then return for on chain punishment**** usermap[msg.sender].hasReportRight[LessorAddress] = false; } //Offer trip section //use DateTime contract before to convert desired Date to uint epoch function offerTrip(uint256 startTime, uint256 endTime, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedLessor(objectType) isNotBlockedLessor { offer memory tempOffer; tempOffer.startTime = startTime; tempOffer.endTime = endTime; tempOffer.latpickupLocation = latpickupLocation; tempOffer.longpickupLocation = longpickupLocation; tempOffer.lessor = msg.sender; tempOffer.price = price; tempOffer.latPolygons = latPolygons; tempOffer.longPolygons = longPolygons; tempOffer.maxReservedAmount = maxReservedAmount; tempOffer.objectType = objectType; tempOffer.model = model; tempOffer.id = indexOfID.length; // set id to the next following tripArray.push(tempOffer); //add trip to the tripArray indexOfID.push(tripArray.length-1); //save location for latest id -> is linked to tempOffer.id from before } //Change Trip details Section //lessors can update object location if not in use or reserved function updateObjectLocation(uint256 id, uint64 newlat, uint64 newlong) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary { require(tripArray[indexOfID[id]].lessor == msg.sender); require(tripArray[indexOfID[id]].reserved == false); tripArray[indexOfID[id]].longpickupLocation = newlong; tripArray[indexOfID[id]].latpickupLocation = newlat; } //lessors can update object price if not in use or reserved function updateObjectPrice(uint256 id, uint256 price) public onlyVerifiedLessor(tripArray[indexOfID[id]].objectType) //modifier might not be neccessary -> check already happened before { require(tripArray[indexOfID[id]].lessor == msg.sender); require(tripArray[indexOfID[id]].reserved == false); tripArray[indexOfID[id]].price = price; } //lessors can delete their offers if not in use or reserved function deleteTrip(uint256 id) public { require(tripArray[indexOfID[id]].reserved == false); require(tripArray[indexOfID[id]].lessor == msg.sender); //trip can only be deleted if not reserved (coveres reserved and started) and if the function is called by the Lessor tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted tripArray.length--; //reduce length of array by one } //maybe restrict function to authorities as its a costly operation, deletes outdated trips from the platform (trips with expired latest return date), frees storage function deleteOutdatedTrips() public { for(uint256 i = 1; i < tripArray.length; i++) //beginning at 1 since 0 trip is not used { if(tripArray[i].endTime < block.timestamp) deleteTripInternal(i); } } //difference from above: Lessor does not have to be msg.sender, gets called by the PlatformContract to delete outdated Trips function deleteTripInternal(uint256 id) internal { require(tripArray[indexOfID[id]].reserved == false); //object can only be rented if not in use tripArray[indexOfID[id]] = tripArray[tripArray.length-1]; //set last element to current element in the Array, thus ovverriting the to be deleted element indexOfID[tripArray[tripArray.length-1].id] = indexOfID[id]; //set the index of the last element to the position it was now switched to delete tripArray[tripArray.length-1]; //delete last element since it got successfully moved indexOfID[id] = 0; //set index of deleted id = 0, indicating it got deleted tripArray.length--; //reduce length of array by one } //Get Trip Information Section function getTrip(uint256 id) public view returns(offer memory) //offer[] memory { return tripArray[indexOfID[id]]; //maybe mapindex has to be set to allow client to refind the trip -> probably better to set this client side when looping } function getLength() public view returns (uint256) //returns total amount of current trips { return tripArray.length; } //index +1 to make 0 distinguishable -no item found function getTripID(uint256 index) public view returns(uint256) { return tripArray[index].id; } //get sum of ratings and amount of ratings, need to be divided client side to retrive actual average rating -> costly operation function getRating(address a) public view returns( uint256[2] memory) { uint256[2] memory ratingArray; ratingArray[0] = usermap[a].rating; ratingArray[1] = usermap[a].ratingCount; return ratingArray; } /** function testGetTokenBalance(bool option) public view returns (uint256) { if(option == false) { return authorityTokens[msg.sender].totalSupply(); } else{ address def; return authorityTokens[def].totalSupply(); } } */ }
use DateTime contract before to convert desired Date to uint epoch
function offerTrip(uint256 startTime, uint256 endTime, uint64 latpickupLocation, uint64 longpickupLocation, uint256 price, uint64[10] memory latPolygons, uint64[10] memory longPolygons, uint256 maxReservedAmount, uint8 objectType, string memory model ) public onlyVerifiedLessor(objectType) isNotBlockedLessor { offer memory tempOffer; tempOffer.startTime = startTime; tempOffer.endTime = endTime; tempOffer.latpickupLocation = latpickupLocation; tempOffer.longpickupLocation = longpickupLocation; tempOffer.lessor = msg.sender; tempOffer.price = price; tempOffer.latPolygons = latPolygons; tempOffer.longPolygons = longPolygons; tempOffer.maxReservedAmount = maxReservedAmount; tempOffer.objectType = objectType; tempOffer.model = model; }
5,489,698
pragma solidity 0.6.12; // SPDX-License-Identifier: BSD-3-Clause /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn'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; } } /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } /** * @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 admin; 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 { admin = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == admin); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(admin, newOwner); admin = newOwner; } } interface Token { function transferFrom(address, address, uint) external returns (bool); function transfer(address, uint) external returns (bool); } contract PoolA is Ownable { using SafeMath for uint; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint amount); event Upline(address indexed addr, address indexed upline); event RewardAllocation(address indexed ref, address indexed _addr, uint bonus); address public tokenAddress; // reward rate % per year uint public rewardRate = 60000; uint public rewardInterval = 365 days; // staking fee percent uint public stakingFeeRate = 0; // unstaking fee percent uint public unstakingFeeRate = 0; // unstaking possible Time uint public PossibleUnstakeTime = 24 hours; uint public totalClaimedRewards = 0; uint private FundedTokens; bool public stakingStatus = false; EnumerableSet.AddressSet private holders; mapping (address => uint) public depositedTokens; mapping (address => uint) public stakingTime; mapping (address => uint) public lastClaimedTime; mapping (address => uint) public totalEarnedTokens; mapping (address => address) public referer; mapping (address => uint) public referrals; mapping (address => uint) public rewardBonuses; uint ref_bonus = 1; /*=============================ADMINISTRATIVE FUNCTIONS ==================================*/ function setTokenAddresses(address _tokenAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0), "Invalid addresses format are not supported"); tokenAddress = _tokenAddr; } function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){ stakingFeeRate = _stakingFeeRate; unstakingFeeRate = _unstakingFeeRate; } function refSet(uint _value) public onlyOwner returns(bool){ ref_bonus = _value; } function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){ rewardRate = _rewardRate; } function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){ FundedTokens = _poolreward; } function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){ PossibleUnstakeTime = _possibleUnstakeTime; } function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){ rewardInterval = _rewardInterval; } function allowStaking(bool _status) public onlyOwner returns(bool){ require(tokenAddress != address(0), "Interracting token address are not yet configured"); stakingStatus = _status; } function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { if (_tokenAddr == tokenAddress) { if (_amount > getFundedTokens()) { revert(); } totalClaimedRewards = totalClaimedRewards.add(_amount); } Token(_tokenAddr).transfer(_to, _amount); } function updateAccount(address account) private { uint unclaimedDivs = getUnclaimedDivs(account); if (unclaimedDivs > 0) { require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs); totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs); emit RewardsTransferred(account, unclaimedDivs); _refPayout(account, unclaimedDivs); } lastClaimedTime[account] = now; } function updateRef(address account) private { uint unclaimedRef = rewardBonuses[account]; if (unclaimedRef > 0) { require(Token(tokenAddress).transfer(account, unclaimedRef), "Could not transfer tokens."); rewardBonuses[account] = rewardBonuses[account].sub(unclaimedRef); } } function getUnclaimedDivs(address _holder) public view returns (uint) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint timeDiff = now.sub(lastClaimedTime[_holder]); uint stakedAmount = depositedTokens[_holder]; uint unclaimedDivs = stakedAmount .mul(rewardRate) .mul(timeDiff) .div(rewardInterval) .div(1e4); return unclaimedDivs; } function getNumberOfHolders() public view returns (uint) { return holders.length(); } function deposit(uint amountToStake, address _upline) public{ _setUpline(msg.sender, _upline); _deposit(amountToStake); } function _deposit(uint amountToStake) internal { require(stakingStatus == true, "Staking is not yet initialized"); require(amountToStake > 0, "Cannot deposit 0 Tokens"); require(referer[msg.sender] != address(0) || msg.sender == admin, "No upline, you need an upline"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); updateAccount(msg.sender); uint fee = amountToStake.mul(stakingFeeRate).div(1e4); uint amountAfterFee = amountToStake.sub(fee); require(Token(tokenAddress).transfer(admin, fee), "Could not transfer deposit fee."); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = now; } } function withdraw(uint amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more"); updateAccount(msg.sender); uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4); uint amountAfterFee = amountToWithdraw.sub(fee); require(Token(tokenAddress).transfer(admin, fee), "Could not transfer withdraw fee."); require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens."); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claim() public { updateAccount(msg.sender); claimRef(); } function claimRef() public { updateRef(msg.sender); } function getFundedTokens() public view returns (uint) { if (totalClaimedRewards >= FundedTokens) { return 0; } uint remaining = FundedTokens.sub(totalClaimedRewards); return remaining; } function _setUpline(address _addr, address _upline) public { if(referer[_addr] == address(0) && _upline != _addr && (stakingTime[_upline] > 0 || _upline == admin)) { referer[_addr] = _upline; referrals[_upline]++; emit Upline(_addr, _upline); } } function _refPayout(address _addr, uint256 _amount) private { address ref = referer[_addr]; if(ref != address(0)){ uint256 bonus = _amount * ref_bonus / 100; rewardBonuses[ref] += bonus; emit RewardAllocation(ref, _addr, bonus); } } }
=============================ADMINISTRATIVE FUNCTIONS ==================================/
function setTokenAddresses(address _tokenAddr) public onlyOwner returns(bool){ require(_tokenAddr != address(0), "Invalid addresses format are not supported"); tokenAddress = _tokenAddr; }
13,808,880
pragma solidity ^0.4.23; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed oldOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner, "msg.sender == owner"); _; } function transferOwnership(address _newOwner) public onlyOwner { require(address(0) != _newOwner, "address(0) != _newOwner"); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner, "msg.sender == newOwner"); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; newOwner = address(0); } } /** * @title Authorizable * @dev The Authorizable contract has authorized addresses, and provides basic authorization control * functions, this simplifies the implementation of "multiple user permissions". */ contract Authorizable is Ownable { mapping(address => bool) public authorized; event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization); /** * @dev The Authorizable constructor sets the first `authorized` of the contract to the sender * account. */ constructor() public { authorized[msg.sender] = true; } /** * @dev Throws if called by any account other than the authorized. */ modifier onlyAuthorized() { require(authorized[msg.sender]); _; } /** * @dev Allows the current owner to set an authorization. * @param addressAuthorized The address to change authorization. */ function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public { emit AuthorizationSet(addressAuthorized, authorization); authorized[addressAuthorized] = authorization; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token from an address to another specified address * @param _sender The address to transfer from. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferFunction(address _sender, address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_to != address(this)); require(_value <= balances[_sender]); // SafeMath.sub will throw if there is not enough balance. balances[_sender] = balances[_sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_sender, _to, _value); return true; } /** * @dev transfer token for a specified address (BasicToken transfer method) */ function transfer(address _to, uint256 _value) public returns (bool) { return transferFunction(msg.sender, _to, _value); } /** * @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 constant returns (uint256 balance) { return balances[_owner]; } } contract ERC223TokenCompatible is BasicToken { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data); // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_to != address(0)); require(_to != address(this)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if( isContract(_to) ) { require(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); } emit Transfer(msg.sender, _to, _value, _data); return true; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) { return transfer( _to, _value, _data, "tokenFallback(address,uint256,bytes)"); } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } } /** * @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(_to != address(this)); 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Startable * @dev Base contract which allows owner to implement an start mechanism without ever being stopped more. */ contract Startable is Ownable, Authorizable { event Start(); bool public started = false; /** * @dev Modifier to make a function callable only when the contract is started. */ modifier whenStarted() { require( started || authorized[msg.sender] ); _; } /** * @dev called by the owner to start, go to normal state */ function start() onlyOwner public { started = true; emit Start(); } } /** * @title Startable token * * @dev StandardToken modified with startable transfers. **/ contract StartToken is Startable, ERC223TokenCompatible, StandardToken { /** ******************************** */ /** START: ADDED BY HORIZON GLOBEX */ /** ******************************** */ // KYC submission hashes accepted by KYC service provider for AML/KYC review. bytes32[] public kycHashes; // All users that have passed the external KYC verification checks. address[] public kycValidated; /** * The hash for all Know Your Customer information is calculated outside but stored here. * This storage will be cleared once the ICO completes, see closeIco(). * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's KYC app will register a hash of the Contributors * KYC submission on the blockchain. Our Swiss financial-intermediary KYC provider will be * notified of the submission and retrieve the Contributor data for formal review. * * All Contributors must successfully complete our ICO KYC review prior to being allowed on-board. * -- End ICO-Platform Note -- * * @param sha The hash of the customer data. */ function setKycHash(bytes32 sha) public onlyOwner { kycHashes.push(sha); } /** * A user has passed KYC verification, store them on the blockchain in the order it happened. * This will be cleared once the ICO completes, see closeIco(). * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's registered KYC provider submits their approval * for this Contributor to particpate using the ICO-Platform portal. * * Each Contributor will then be sent the Ethereum, Bitcoin and IBAN account numbers to * deposit their Approved Contribution in exchange for VOX Tokens. * -- End ICO-Platform Note -- * * @param who The user's address. */ function kycApproved(address who) public onlyOwner { require(who != 0x0, "Cannot approve a null address."); kycValidated.push(who); } /** * Retrieve the KYC hash from the specified index. * * @param index The index into the array. */ function getKycHash(uint256 index) public view returns (bytes32) { return kycHashes[index]; } /** * Retrieve the validated KYC address from the specified index. * * @param index The index into the array. */ function getKycApproved(uint256 index) public view returns (address) { return kycValidated[index]; } /** * During the ICO phase the owner will allocate tokens once KYC completes and funds are deposited. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's portal shall issue VOX Token to Contributors on receipt of * the Approved Contribution funds at the KYC providers Escrow account/wallets. * Only after VOX Tokens are issued to the Contributor can the Swiss KYC provider allow the transfer * of funds from their Escrow to Company. * * -- End ICO-Platform Note -- * * @param to The recipient of the tokens. * @param value The number of tokens to send. */ function icoTransfer(address to, uint256 value) public onlyOwner { // If an attempt is made to transfer more tokens than owned, transfer the remainder. uint256 toTransfer = (value > (balances[msg.sender])) ? (balances[msg.sender]) : value; transferFunction(msg.sender, to, toTransfer); } /** ******************************** */ /** END: ADDED BY HORIZON GLOBEX */ /** ******************************** */ function transfer(address _to, uint256 _value) public whenStarted returns (bool) { return super.transfer(_to, _value); } function transfer(address _to, uint256 _value, bytes _data) public whenStarted returns (bool) { return super.transfer(_to, _value, _data); } function transfer(address _to, uint256 _value, bytes _data, string _custom_fallback) public whenStarted returns (bool) { return super.transfer(_to, _value, _data, _custom_fallback); } function transferFrom(address _from, address _to, uint256 _value) public whenStarted returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenStarted returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenStarted returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenStarted returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract HumanStandardToken is StandardToken, StartToken { /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { approve(_spender, _value); require(_spender.call(bytes4(keccak256("receiveApproval(address,uint256,bytes)")), msg.sender, _value, _extraData)); return true; } } contract BurnToken is StandardToken { uint256 public initialSupply; event Burn(address indexed burner, uint256 value); /** * @dev Function to burn tokens. * @param _burner The address of token holder. * @param _value The amount of token to be burned. */ function burnFunction(address _burner, uint256 _value) internal returns (bool) { require(_value > 0); require(_value <= balances[_burner]); // 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[_burner] = balances[_burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_burner, _value); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns(bool) { return burnFunction(msg.sender, _value); } /** * @dev Burns tokens from one address * @param _from address The address which you want to burn tokens from * @param _value uint256 the amount of tokens to be burned */ function burnFrom(address _from, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); // check if it has the budget allowed burnFunction(_from, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } } contract Token is ERC223TokenCompatible, StandardToken, StartToken, HumanStandardToken { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[msg.sender] = totalSupply; } } contract TokenBurn is Token, BurnToken { constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public Token(_name, _symbol, _decimals, _totalSupply) { initialSupply = totalSupply; } }
Allows the current owner to set an authorization. addressAuthorized The address to change authorization./
function setAuthorized(address addressAuthorized, bool authorization) onlyOwner public { emit AuthorizationSet(addressAuthorized, authorization); authorized[addressAuthorized] = authorization; }
12,976,921
./full_match/122/0xCbc6Ce8C3bc4E5D7EB0fe7440B7b0f58C2884D3B/sources/contracts/LiquidStakingPool.sol
Returns the current number of validators on list/
function getValidatorsLength() public view returns (uint256) { address[] memory validatorList = getValidators(); return validatorList.length; }
16,366,552
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: UNLICENSED /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity 0.8.11; library BytesLib { function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IIdleToken { function decimals() external view returns (uint8); function getGovTokens() external view returns (address[] memory); function tokenPriceWithFee(address user) external view returns (uint256); function balanceOf(address user) external view returns (uint256); function redeemIdleToken(uint256 amount) external; function mintIdleToken( uint256 amount, bool, address referral ) external returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IV2SwapRouter.sol'; import './IV3SwapRouter.sol'; /// @title Router token swapping functionality interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V2 interface IV2SwapRouter { /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @param amountIn The amount of token to swap /// @param amountOutMin The minimum amount of output that must be received /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountOut The amount of the received token function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to ) external payable returns (uint256 amountOut); /// @notice Swaps as little as possible of one token for an exact amount of another token /// @param amountOut The amount of token to swap for /// @param amountInMax The maximum amount of input that the caller will pay /// @param path The ordered list of tokens to swap through /// @param to The recipient address /// @return amountIn The amount of token to pay function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to ) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IV3SwapRouter{ struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @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 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance, /// and swap the entire amount, enabling contracts to send tokens before calling this function. /// @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 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// that may remain in the router after the swap. /// @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 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// that may remain in the router after the swap. /// @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: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; import "./ISwapData.sol"; interface IBaseStrategy { function underlying() external view returns (IERC20); function getStrategyBalance() external view returns (uint128); function getStrategyUnderlyingWithRewards() external view returns(uint128); function process(uint256[] calldata, bool, SwapData[] calldata) external; function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128); function processDeposit(uint256[] calldata) external; function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128); function claimRewards(SwapData[] calldata) external; function emergencyWithdraw(address recipient, uint256[] calldata data) external; function initialize() external; function disable() external; } struct ProcessReallocationData { uint128 sharesToWithdraw; uint128 optimizedShares; uint128 optimizedWithdrawnAmount; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; /** * @notice Strict holding information how to swap the asset * @member slippage minumum output amount * @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path */ struct SwapData { uint256 slippage; // min amount out bytes path; // 1st byte is action, then path } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "../external/@openzeppelin/utils/SafeCast.sol"; /** * @notice A collection of custom math ustils used throughout the system */ library Math { function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { return SafeCast.toUint128(((mul1 * mul2) / div)); } function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) { unchecked { return uint128((mul1 * mul2) / div); } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /** @notice Handle setting zero value in a storage word as uint128 max value. * * @dev * The purpose of this is to avoid resetting a storage word to the zero value; * the gas cost of re-initializing the value is the same as setting the word originally. * so instead, if word is to be set to zero, we set it to uint128 max. * * - anytime a word is loaded from storage: call "get" * - anytime a word is written to storage: call "set" * - common operations on uints are also bundled here. * * NOTE: This library should ONLY be used when reading or writing *directly* from storage. */ library Max128Bit { uint128 internal constant ZERO = type(uint128).max; function get(uint128 a) internal pure returns(uint128) { return (a == ZERO) ? 0 : a; } function set(uint128 a) internal pure returns(uint128){ return (a == 0) ? ZERO : a; } function add(uint128 a, uint128 b) internal pure returns(uint128 c){ a = get(a); c = set(a + b); } } // SPDX-License-Identifier: BUSL-1.1 import "../interfaces/ISwapData.sol"; pragma solidity 0.8.11; /// @notice Strategy struct for all strategies struct Strategy { uint128 totalShares; /// @notice Denotes strategy completed index uint24 index; /// @notice Denotes whether strategy is removed /// @dev after removing this value can never change, hence strategy cannot be added back again bool isRemoved; /// @notice Pending geposit amount and pending shares withdrawn by all users for next index Pending pendingUser; /// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index Pending pendingUserNext; /// @dev Usually a temp variable when compounding mapping(address => uint256) pendingRewards; /// @dev Usually a temp variable when compounding uint128 pendingDepositReward; /// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it uint256 lpTokens; // ----- REALLOCATION VARIABLES ----- bool isInDepositPhase; /// @notice Used to store amount of optimized shares, so they can be substracted at the end /// @dev Only for temporary use, should be reset to 0 in same transaction uint128 optimizedSharesWithdrawn; /// @dev Underlying amount pending to be deposited from other strategies at reallocation /// @dev resets after the strategy reallocation DHW is finished uint128 pendingReallocateDeposit; /// @notice Stores amount of optimized underlying amount when reallocating /// @dev resets after the strategy reallocation DHW is finished /// @dev This is "virtual" amount that was matched between this strategy and others when reallocating uint128 pendingReallocateOptimizedDeposit; // ------------------------------------ /// @notice Total underlying amoung at index mapping(uint256 => TotalUnderlying) totalUnderlying; /// @notice Batches stored after each DHW with index as a key /// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users mapping(uint256 => Batch) batches; /// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate) /// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation mapping(uint256 => BatchReallocation) reallocationBatches; /// @notice Vaults holding this strategy shares mapping(address => Vault) vaults; /// @notice Future proof storage mapping(bytes32 => AdditionalStorage) additionalStorage; /// @dev Make sure to reset it to 0 after emergency withdrawal uint256 emergencyPending; } /// @notice Unprocessed deposit underlying amount and strategy share amount from users struct Pending { uint128 deposit; uint128 sharesToWithdraw; } /// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index struct TotalUnderlying { uint128 amount; uint128 totalShares; } /// @notice Stored after executing DHW for each index. /// @dev This is used for vaults to redeem their deposit. struct Batch { /// @notice total underlying deposited in index uint128 deposited; uint128 depositedReceived; uint128 depositedSharesReceived; uint128 withdrawnShares; uint128 withdrawnReceived; } /// @notice Stored after executing reallocation DHW each index. struct BatchReallocation { /// @notice Deposited amount received from reallocation uint128 depositedReallocation; /// @notice Received shares from reallocation uint128 depositedReallocationSharesReceived; /// @notice Used to know how much tokens was received for reallocating uint128 withdrawnReallocationReceived; /// @notice Amount of shares to withdraw for reallocation uint128 withdrawnReallocationShares; } /// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working) struct Vault { uint128 shares; /// @notice Withdrawn amount as part of the reallocation uint128 withdrawnReallocationShares; /// @notice Index to action mapping(uint256 => VaultBatch) vaultBatches; } /// @notice Stores deposited and withdrawn shares by the vault struct VaultBatch { /// @notice Vault index to deposited amount mapping uint128 deposited; /// @notice Vault index to withdrawn user shares mapping uint128 withdrawnShares; } /// @notice Used for reallocation calldata struct VaultData { address vault; uint8 strategiesCount; uint256 strategiesBitwise; uint256 newProportions; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the withdraw part of the reallocation DHW struct ReallocationWithdrawData { uint256[][] reallocationTable; StratUnderlyingSlippage[] priceSlippages; RewardSlippages[] rewardSlippages; uint256[] stratIndexes; uint256[][] slippages; } /// @notice Calldata when executing reallocatin DHW /// @notice Used in the deposit part of the reallocation DHW struct ReallocationData { uint256[] stratIndexes; uint256[][] slippages; } /// @notice In case some adapters need extra storage struct AdditionalStorage { uint256 value; address addressValue; uint96 value96; } /// @notice Strategy total underlying slippage, to verify validity of the strategy state struct StratUnderlyingSlippage { uint128 min; uint128 max; } /// @notice Containig information if and how to swap strategy rewards at the DHW /// @dev Passed in by the do-hard-worker struct RewardSlippages { bool doClaim; SwapData[] swapData; } /// @notice Helper struct to compare strategy share between eachother /// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating) struct PriceData { uint128 totalValue; uint128 totalShares; } /// @notice Strategy reallocation values after reallocation optimization of shares was calculated struct ReallocationShares { uint128[] optimizedWithdraws; uint128[] optimizedShares; uint128[] totalSharesWithdrawn; } /// @notice Shared storage for multiple strategies /// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool) struct StrategiesShared { uint184 value; uint32 lastClaimBlock; uint32 lastUpdateBlock; uint8 stratsCount; mapping(uint256 => address) stratAddresses; mapping(bytes32 => uint256) bytesValues; } /// @notice Base storage shared betweek Spool contract and Strategies /// @dev this way we can use same values when performing delegate call /// to strategy implementations from the Spool contract abstract contract BaseStorage { // ----- DHW VARIABLES ----- /// @notice Force while DHW (all strategies) to be executed in only one transaction /// @dev This is enforced to increase the gas efficiency of the system /// Can be removed by the DAO if gas gost of the strategies goes over the block limit bool internal forceOneTxDoHardWork; /// @notice Global index of the system /// @dev Insures the correct strategy DHW execution. /// Every strategy in the system must be equal or one less than global index value /// Global index increments by 1 on every do-hard-work uint24 public globalIndex; /// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed uint8 internal doHardWorksLeft; // ----- REALLOCATION VARIABLES ----- /// @notice Used for offchain execution to get the new reallocation table. bool internal logReallocationTable; /// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index /// @dev only used when reallocating /// after it reaches 0, deposit phase of the reallocation can begin uint8 public withdrawalDoHardWorksLeft; /// @notice Index at which next reallocation is set uint24 public reallocationIndex; /// @notice 2D table hash containing information of how strategies should be reallocated between eachother /// @dev Created when allocation provider sets reallocation for the vaults /// This table is stored as a hash in the system and verified on reallocation DHW /// Resets to 0 after reallocation DHW is completed bytes32 internal reallocationTableHash; /// @notice Hash of all the strategies array in the system at the time when reallocation was set for index /// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating. /// This way we can remove the strategy from the system and not breaking the flow of the reallocaton /// Resets when DHW is completed bytes32 internal reallocationStrategiesHash; // ----------------------------------- /// @notice Denoting if an address is the do-hard-worker mapping(address => bool) public isDoHardWorker; /// @notice Denoting if an address is the allocation provider mapping(address => bool) public isAllocationProvider; /// @notice Strategies shared storage /// @dev used as a helper storage to save common inoramation mapping(bytes32 => StrategiesShared) internal strategiesShared; /// @notice Mapping of strategy implementation address to strategy system values mapping(address => Strategy) public strategies; /// @notice Flag showing if disable was skipped when a strategy has been removed /// @dev If true disable can still be run mapping(address => bool) internal _skippedDisable; /// @notice Flag showing if after removing a strategy emergency withdraw can still be executed /// @dev If true emergency withdraw can still be executed mapping(address => bool) internal _awaitingEmergencyWithdraw; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; /// @title Common Spool contracts constants abstract contract BaseConstants { /// @dev 2 digits precision uint256 internal constant FULL_PERCENT = 100_00; /// @dev Accuracy when doing shares arithmetics uint256 internal constant ACCURACY = 10**30; } /// @title Contains USDC token related values abstract contract USDC { /// @notice USDC token contract address IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../external/GNSPS-solidity-bytes-utils/BytesLib.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../external/uniswap/interfaces/ISwapRouter02.sol"; import "../interfaces/ISwapData.sol"; /// @notice Denotes swap action mode enum SwapAction { NONE, UNI_V2_DIRECT, UNI_V2_WETH, UNI_V2, UNI_V3_DIRECT, UNI_V3_WETH, UNI_V3 } /// @title Contains logic facilitating swapping using Uniswap abstract contract SwapHelper { using BytesLib for bytes; using SafeERC20 for IERC20; /// @dev The length of the bytes encoded swap action uint256 private constant ACTION_SIZE = 1; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev Maximum V2 path length (4 swaps) uint256 private constant MAX_V2_PATH = ADDR_SIZE * 3; /// @dev V3 WETH path length uint256 private constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE; /// @dev Minimum V3 custom path length (2 swaps) uint256 private constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET; /// @dev Maximum V3 path length (4 swaps) uint256 private constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3; /// @notice Uniswap router supporting Uniswap V2 and V3 ISwapRouter02 internal immutable uniswapRouter; /// @notice Address of WETH token address private immutable WETH; /** * @notice Sets initial values * @param _uniswapRouter Uniswap router address * @param _WETH WETH token address */ constructor(ISwapRouter02 _uniswapRouter, address _WETH) { uniswapRouter = _uniswapRouter; WETH = _WETH; } /** * @notice Approve reward token and swap the `amount` to a strategy underlying asset * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param swapData Swap details showing the path of the swap * @return result Amount of underlying (`to`) tokens recieved */ function _approveAndSwap( IERC20 from, IERC20 to, uint256 amount, SwapData calldata swapData ) internal virtual returns (uint256) { // if there is nothing to swap, return if(amount == 0) return 0; // if amount is not uint256 max approve unswap router to spend tokens // otherwise rewards were already sent to the router if(amount < type(uint256).max) { from.safeApprove(address(uniswapRouter), amount); } else { amount = 0; } // get swap action from first byte SwapAction action = SwapAction(swapData.path.toUint8(0)); uint256 result; if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct address[] memory path = new address[](2); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH address[] memory path = new address[](3); path[1] = WETH; result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V2) { // V2 Custom address[] memory path = _getV2Path(swapData.path); result = _swapV2(from, to, amount, swapData.slippage, path); } else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path); } else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH bytes memory wethPath = _getV3WethPath(swapData.path); result = _swapV3(from, to, amount, swapData.slippage, wethPath); } else if (action == SwapAction.UNI_V3) { // V3 Custom require(swapData.path.length > MIN_V3_PATH, "SwapHelper::_approveAndSwap: Path too short"); uint256 actualpathSize = swapData.path.length - ACTION_SIZE; require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 && actualpathSize <= MAX_V3_PATH, "SwapHelper::_approveAndSwap: Bad V3 path"); result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]); } else { revert("SwapHelper::_approveAndSwap: No action"); } if (from.allowance(address(this), address(uniswapRouter)) > 0) { from.safeApprove(address(uniswapRouter), 0); } return result; } /** * @notice Swaps tokens using Uniswap V2 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV2( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, address[] memory path ) internal virtual returns (uint256) { path[0] = address(from); path[path.length - 1] = address(to); return uniswapRouter.swapExactTokensForTokens( amount, slippage, path, address(this) ); } /** * @notice Swaps tokens using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param path Steps to complete the swap * @return result Amount of underlying (`to`) tokens recieved */ function _swapV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory path ) internal virtual returns (uint256) { IV3SwapRouter.ExactInputParams memory params = IV3SwapRouter.ExactInputParams({ path: abi.encodePacked(address(from), path, address(to)), recipient: address(this), amountIn: amount, amountOutMinimum: slippage }); // Executes the swap. uint received = uniswapRouter.exactInput(params); return received; } /** * @notice Does a direct swap from `from` address to the `to` address using Uniswap V3 * @param from Token to swap from * @param to Token to swap to * @param amount Amount of tokens to swap * @param slippage Allowed slippage * @param fee V3 direct fee configuration * @return result Amount of underlying (`to`) tokens recieved */ function _swapDirectV3( IERC20 from, IERC20 to, uint256 amount, uint256 slippage, bytes memory fee ) internal virtual returns (uint256) { require(fee.length == FEE_SIZE + ACTION_SIZE, "SwapHelper::_swapDirectV3: Bad V3 direct fee"); IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams( address(from), address(to), // ignore first byte fee.toUint24(ACTION_SIZE), address(this), amount, slippage, 0 ); return uniswapRouter.exactInputSingle(params); } /** * @notice Converts passed bytes to V2 path * @param pathBytes Swap path in bytes, converted to addresses * @return path list of addresses in the swap path (skipping first and last element) */ function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) { require(pathBytes.length > ACTION_SIZE, "SwapHelper::_getV2Path: No path provided"); uint256 actualpathSize = pathBytes.length - ACTION_SIZE; require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, "SwapHelper::_getV2Path: Bad V2 path"); uint256 pathLength = actualpathSize / ADDR_SIZE; address[] memory path = new address[](pathLength + 2); // ignore first byte path[1] = pathBytes.toAddress(ACTION_SIZE); for (uint256 i = 1; i < pathLength; i++) { path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE); } return path; } /** * @notice Get Unswap V3 path to swap tokens via WETH LP pool * @param pathBytes Swap path in bytes * @return wethPath Unswap V3 path routing via WETH pool */ function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) { require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, "SwapHelper::_getV3WethPath: Bad V3 WETH path"); // ignore first byte as it's used for swap action return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./SwapHelper.sol"; /// @title Swap helper implementation with SwapRouter02 on Mainnet contract SwapHelperMainnet is SwapHelper { constructor() SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) {} } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../interfaces/IBaseStrategy.sol"; import "../shared/BaseStorage.sol"; import "../shared/Constants.sol"; import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "../libraries/Math.sol"; import "../libraries/Max/128Bit.sol"; /** * @notice Implementation of the {IBaseStrategy} interface. * * @dev * This implementation of the {IBaseStrategy} is meant to operate * on single-collateral strategies and uses a delta system to calculate * whether a withdrawal or deposit needs to be performed for a particular * strategy. */ abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants { using SafeERC20 for IERC20; using Max128Bit for uint128; /* ========== CONSTANTS ========== */ /// @notice minimum shares size to avoid loss of share due to computation precision uint128 private constant MIN_SHARES = 10**8; /* ========== STATE VARIABLES ========== */ /// @notice The total slippage slots the strategy supports, used for validation of provided slippage uint256 internal immutable rewardSlippageSlots; /// @notice Slots for processing uint256 internal immutable processSlippageSlots; /// @notice Slots for reallocation uint256 internal immutable reallocationSlippageSlots; /// @notice Slots for deposit uint256 internal immutable depositSlippageSlots; /** * @notice do force claim of rewards. * * @dev * Some strategies auto claim on deposit/withdraw, * so execute the claim actions to store the reward amounts. */ bool internal immutable forceClaim; /// @notice flag to force balance validation before running process strategy /// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system bool internal immutable doValidateBalance; /// @notice The self address, set at initialization to allow proper share accounting address internal immutable self; /// @notice The underlying asset of the strategy IERC20 public immutable override underlying; /* ========== CONSTRUCTOR ========== */ /** * @notice Initializes the base strategy values. * * @dev * It performs certain pre-conditional validations to ensure the contract * has been initialized properly, such as that the address argument of the * underlying asset is valid. * * Slippage slots for certain strategies may be zero if there is no compounding * work to be done. * * @param _underlying token used for deposits * @param _rewardSlippageSlots slots for rewards * @param _processSlippageSlots slots for processing * @param _reallocationSlippageSlots slots for reallocation * @param _depositSlippageSlots slots for deposits * @param _forceClaim force claim of rewards * @param _doValidateBalance force balance validation */ constructor( IERC20 _underlying, uint256 _rewardSlippageSlots, uint256 _processSlippageSlots, uint256 _reallocationSlippageSlots, uint256 _depositSlippageSlots, bool _forceClaim, bool _doValidateBalance ) { require( _underlying != IERC20(address(0)), "BaseStrategy::constructor: Underlying address cannot be 0" ); self = address(this); underlying = _underlying; rewardSlippageSlots = _rewardSlippageSlots; processSlippageSlots = _processSlippageSlots; reallocationSlippageSlots = _reallocationSlippageSlots; depositSlippageSlots = _depositSlippageSlots; forceClaim = _forceClaim; doValidateBalance = _doValidateBalance; } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Process the latest pending action of the strategy * * @dev * it yields amount of funds processed as well as the reward buffer of the strategy. * The function will auto-compound rewards if requested and supported. * * Requirements: * * - the slippages provided must be valid in length * - if the redeposit flag is set to true, the strategy must support * compounding of rewards * * @param slippages slippages to process * @param redeposit if redepositing is to occur * @param swapData swap data for processing */ function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override { slippages = _validateStrategyBalance(slippages); if (forceClaim || redeposit) { _validateRewardsSlippage(swapData); _processRewards(swapData); } if (processSlippageSlots != 0) _validateProcessSlippage(slippages); _process(slippages, 0); } /** * @notice Process first part of the reallocation DHW * @dev Withdraws for reallocation, depositn and withdraww for a user * * @param slippages Parameters to apply when performing a deposit or a withdraw * @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw * @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw */ function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); if (reallocationSlippageSlots != 0) _validateReallocationSlippage(slippages); _process(slippages, processReallocationData.sharesToWithdraw); uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData); return withdrawnReallocationReceived; } /** * @dev Update reallocation batch storage for index after withdrawing reallocated shares * @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw * @return Withdrawn reallocation received */ function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint24 stratIndex = _getProcessingIndex(); BatchReallocation storage batch = strategy.reallocationBatches[stratIndex]; // save actual withdrawn amount, without optimized one uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived; strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares; batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount; batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw; return withdrawnReallocationReceived; } /** * @notice Process deposit * @param slippages Array of slippage parameters to apply when depositing */ function processDeposit(uint256[] calldata slippages) external override { slippages = _validateStrategyBalance(slippages); if (depositSlippageSlots != 0) _validateDepositSlippage(slippages); _processDeposit(slippages); } /** * @notice Returns total starategy balance includign pending rewards * @return strategyBalance total starategy balance includign pending rewards */ function getStrategyUnderlyingWithRewards() public view override returns(uint128) { return _getStrategyUnderlyingWithRewards(); } /** * @notice Fast withdraw * @param shares Shares to fast withdraw * @param slippages Array of slippage parameters to apply when withdrawing * @param swapData Swap slippage and path array * @return Withdrawn amount withdawn */ function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128) { slippages = _validateStrategyBalance(slippages); _validateRewardsSlippage(swapData); if (processSlippageSlots != 0) _validateProcessSlippage(slippages); uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData); strategies[self].totalShares -= shares; return withdrawnAmount; } /** * @notice Claims and possibly compounds strategy rewards. * * @param swapData swap data for processing */ function claimRewards(SwapData[] calldata swapData) external override { _validateRewardsSlippage(swapData); _processRewards(swapData); } /** * @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process. * * @param recipient recipient of the withdrawn funds * @param data data necessary execute the emergency withdraw */ function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override { uint256 balanceBefore = underlying.balanceOf(address(this)); _emergencyWithdraw(recipient, data); uint256 balanceAfter = underlying.balanceOf(address(this)); uint256 withdrawnAmount = 0; if (balanceAfter > balanceBefore) { withdrawnAmount = balanceAfter - balanceBefore; } Strategy storage strategy = strategies[self]; if (strategy.emergencyPending > 0) { withdrawnAmount += strategy.emergencyPending; strategy.emergencyPending = 0; } // also withdraw all unprocessed deposit for a strategy if (strategy.pendingUser.deposit.get() > 0) { withdrawnAmount += strategy.pendingUser.deposit.get(); strategy.pendingUser.deposit = 0; } if (strategy.pendingUserNext.deposit.get() > 0) { withdrawnAmount += strategy.pendingUserNext.deposit.get(); strategy.pendingUserNext.deposit = 0; } // if strategy was already processed in the current index that hasn't finished yet, // transfer the withdrawn amount // reset total underlying to 0 if (strategy.index == globalIndex && doHardWorksLeft > 0) { uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived; withdrawnAmount += withdrawnReceived; strategy.batches[strategy.index].withdrawnReceived = 0; strategy.totalUnderlying[strategy.index].amount = 0; } if (withdrawnAmount > 0) { // check if the balance is high enough to withdraw the total withdrawnAmount if (balanceAfter < withdrawnAmount) { // if not withdraw the current balance withdrawnAmount = balanceAfter; } underlying.safeTransfer(recipient, withdrawnAmount); } } /** * @notice Initialize a strategy. * @dev Execute strategy specific one-time actions if needed. */ function initialize() external virtual override {} /** * @notice Disables a strategy. * @dev Cleans strategy specific values if needed. */ function disable() external virtual override {} /* ========== INTERNAL FUNCTIONS ========== */ /** * @dev Validate strategy balance * @param slippages Check if the strategy balance is within defined min and max values * @return slippages Same array without first 2 slippages */ function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) { if (doValidateBalance) { require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages"); uint128 strategyBalance = getStrategyBalance(); require( slippages[0] <= strategyBalance && slippages[1] >= strategyBalance, "BaseStrategy::_validateStrategyBalance: Bad strategy balance" ); return slippages[2:]; } return slippages; } /** * @dev Validate reards slippage * @param swapData Swap slippage and path array */ function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual { if (swapData.length > 0) { require( swapData.length == _getRewardSlippageSlots(), "BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined" ); } } /** * @dev Retrieve reward slippage slots * @return Reward slippage slots */ function _getRewardSlippageSlots() internal view virtual returns(uint256) { return rewardSlippageSlots; } /** * @dev Validate process slippage * @param slippages parameters to verify validity of the strategy state */ function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, processSlippageSlots); } /** * @dev Validate reallocation slippage * @param slippages parameters to verify validity of the strategy state */ function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, reallocationSlippageSlots); } /** * @dev Validate deposit slippage * @param slippages parameters to verify validity of the strategy state */ function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual { _validateSlippage(slippages.length, depositSlippageSlots); } /** * @dev Validates the provided slippage in length. * @param currentLength actual slippage array length * @param shouldBeLength expected slippages array length */ function _validateSlippage(uint256 currentLength, uint256 shouldBeLength) internal view virtual { require( currentLength == shouldBeLength, "BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined" ); } /** * @dev Retrieve processing index * @return Processing index */ function _getProcessingIndex() internal view returns(uint24) { return strategies[self].index + 1; } /** * @dev Calculates shares before they are added to the total shares * @param strategyTotalShares Total shares for strategy * @param stratTotalUnderlying Total underlying for strategy * @return newShares New shares calculated */ function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ uint128 oldUnderlying; if (stratTotalUnderlying > depositAmount) { oldUnderlying = stratTotalUnderlying - depositAmount; } if (strategyTotalShares == 0 || oldUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying); } } /** * @dev Calculates shares when they are already part of the total shares * * @param strategyTotalShares Total shares * @param stratTotalUnderlying Total underlying * @return newShares New shares calculated */ function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){ if (strategyTotalShares == 0 || stratTotalUnderlying == 0) { // Enforce minimum shares size to avoid loss of share due to computation precision newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount; } else { newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying); } } /** * @dev Reset allowance to zero if previously set to a higher value. * @param token Asset * @param spender Spender address */ function _resetAllowance(IERC20 token, address spender) internal { if (token.allowance(address(this), spender) > 0) { token.safeApprove(spender, 0); } } /* ========== VIRTUAL FUNCTIONS ========== */ function getStrategyBalance() public view virtual override returns (uint128); function _processRewards(SwapData[] calldata) internal virtual; function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual; function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual; function _processDeposit(uint256[] memory) internal virtual; function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128); function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./RewardStrategy.sol"; import "../shared/SwapHelperMainnet.sol"; /** * @notice Multiple reward strategy logic */ abstract contract MultipleRewardStrategy is RewardStrategy, SwapHelperMainnet { /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Claim rewards * @param swapData Slippage and path array * @return Rewards */ function _claimRewards(SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) { return _claimMultipleRewards(type(uint128).max, swapData); } /** * @dev Claim fast withdraw rewards * @param shares Amount of shares * @param swapData Swap slippage and path * @return Rewards */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual override returns(Reward[] memory) { return _claimMultipleRewards(shares, swapData); } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimMultipleRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./BaseStrategy.sol"; import "../libraries/Max/128Bit.sol"; import "../libraries/Math.sol"; struct ProcessInfo { uint128 totalWithdrawReceived; uint128 userDepositReceived; } /** * @notice Process strategy logic */ abstract contract ProcessStrategy is BaseStrategy { using Max128Bit for uint128; /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards * @dev * Deposit amount amd withdrawal shares are matched between eachother, effecively only one of * those 2 is called. Shares are converted to the dollar value, based on the current strategy * total balance. This ensures the minimum amount of assets are moved around to lower the price * drift and total fees paid to the protocols the strategy is interacting with (if there are any) * * @param slippages Strategy slippage values verifying the validity of the strategy state * @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0) */ function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual { // PREPARE Strategy storage strategy = strategies[self]; uint24 processingIndex = _getProcessingIndex(); Batch storage batch = strategy.batches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get(); uint128 userDeposit = strategy.pendingUser.deposit.get(); // CALCULATE THE ACTION // if withdrawing for reallocating, add shares to total withdraw shares if (reallocateSharesToWithdraw > 0) { pendingSharesToWithdraw += reallocateSharesToWithdraw; } // total deposit received from users + compound reward (if there are any) uint128 totalPendingDeposit = userDeposit; // add compound reward (pendingDepositReward) to deposit uint128 withdrawalReward = 0; if (strategy.pendingDepositReward > 0) { uint128 pendingDepositReward = strategy.pendingDepositReward; totalPendingDeposit += pendingDepositReward; // calculate compound reward (withdrawalReward) for users withdrawing in this batch if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) { withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares); // substract withdrawal reward from total deposit totalPendingDeposit -= withdrawalReward; } // Reset pendingDepositReward strategy.pendingDepositReward = 0; } // if there is no pending deposit or withdrawals, return if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) { return; } uint128 pendingWithdrawalAmount = 0; if (pendingSharesToWithdraw > 0) { pendingWithdrawalAmount = Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares); } // ACTION: DEPOSIT OR WITHDRAW ProcessInfo memory processInfo; if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT // uint128 amount = totalPendingDeposit - pendingWithdrawalAmount; uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages); processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; // pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount; uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount; // calculate user deposit received, excluding compound rewards processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit); } else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW // uint128 amount = pendingWithdrawalAmount - totalPendingDeposit; uint128 withdrawReceived = _withdraw( // calculate back the shares from actual withdraw amount // NOTE: we can do unchecked calculation and casting as // the multiplier is always smaller than the divisor Math.getProportion128Unchecked( (pendingWithdrawalAmount - totalPendingDeposit), pendingSharesToWithdraw, pendingWithdrawalAmount ), slippages ); // optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit; processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward; processInfo.userDepositReceived = userDeposit; } else { processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward; processInfo.userDepositReceived = userDeposit; } // UPDATE STORAGE AFTER { uint128 stratTotalUnderlying = getStrategyBalance(); // Update withdraw batch if (pendingSharesToWithdraw > 0) { batch.withdrawnReceived = processInfo.totalWithdrawReceived; batch.withdrawnShares = pendingSharesToWithdraw; strategyTotalShares -= pendingSharesToWithdraw; // update reallocation batch if (reallocateSharesToWithdraw > 0) { BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 withdrawnReallocationReceived = Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw); reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived; // substract reallocation values from user values batch.withdrawnReceived -= withdrawnReallocationReceived; batch.withdrawnShares -= reallocateSharesToWithdraw; } } // Update deposit batch if (userDeposit > 0) { uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived); batch.deposited = userDeposit; batch.depositedReceived = processInfo.userDepositReceived; batch.depositedSharesReceived = newShares; strategyTotalShares += newShares; } // Update shares if (strategyTotalShares != strategy.totalShares) { strategy.totalShares = strategyTotalShares; } // Set underlying at index strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; } } /** * @notice Process deposit * @param slippages Slippages array */ function _processDeposit(uint256[] memory slippages) internal override virtual { Strategy storage strategy = strategies[self]; uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit; uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn; uint128 depositAmount = strategy.pendingReallocateDeposit; // if a strategy is not part of reallocation return if ( depositOptimizedAmount == 0 && optimizedSharesWithdrawn == 0 && depositAmount == 0 ) { return; } uint24 processingIndex = _getProcessingIndex(); BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex]; uint128 strategyTotalShares = strategy.totalShares; // get shares from optimized deposit if (depositOptimizedAmount > 0) { uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation = depositOptimizedAmount; reallocationBatch.depositedReallocationSharesReceived = newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateOptimizedDeposit = 0; } // remove optimized withdraw shares if (optimizedSharesWithdrawn > 0) { strategyTotalShares -= optimizedSharesWithdrawn; // reset strategy.optimizedSharesWithdrawn = 0; } // get shares from actual deposit if (depositAmount > 0) { // deposit uint128 depositReceived = _deposit(depositAmount, slippages); // NOTE: might return it from _deposit (only certain strategies need it) uint128 stratTotalUnderlying = getStrategyBalance(); uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived); // add new shares strategyTotalShares += newShares; // update reallocation batch reallocationBatch.depositedReallocation += depositReceived; reallocationBatch.depositedReallocationSharesReceived += newShares; strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying; // reset strategy.pendingReallocateDeposit = 0; } // update share storage strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares; strategy.totalShares = strategyTotalShares; } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice get the value of the strategy shares in the underlying tokens * @param shares Number of shares * @return amount Underling amount representing the `share` value of the strategy */ function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) { amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares ); } /** * @notice get slippage amount, and action type (withdraw/deposit). * @dev * Most significant bit represents an action, 0 for a withdrawal and 1 for deposit. * * This ensures the slippage will be used for the action intended by the do-hard-worker, * otherwise the transavtion will revert. * * @param slippageAction number containing the slippage action and the actual slippage amount * @return isDeposit Flag showing if the slippage is for the deposit action * @return slippage the slippage value cleaned of the most significant bit */ function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) { // remove most significant bit slippage = (slippageAction << 1) >> 1; // if values are not the same (the removed bit was 1) set action to deposit if (slippageAction != slippage) { isDeposit = true; } } /* ========== VIRTUAL FUNCTIONS ========== */ function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived); function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "./ProcessStrategy.sol"; import "../shared/SwapHelper.sol"; struct Reward { uint256 amount; IERC20 token; } /** * @notice Reward strategy logic */ abstract contract RewardStrategy is ProcessStrategy, SwapHelper { /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Gey strategy underlying asset with rewards * @return Total underlying */ function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) { Strategy storage strategy = strategies[self]; uint128 totalUnderlying = getStrategyBalance(); totalUnderlying += strategy.pendingDepositReward; return totalUnderlying; } /** * @notice Process an instant withdrawal from the protocol per users request. * * @param shares Amount of shares * @param slippages Array of slippages * @param swapData Data used in processing * @return Withdrawn amount */ function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) { uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData); uint128 withdrawReceived = _withdraw(shares, slippages); return withdrawReceived + withdrawRewards; } /** * @notice Process rewards * @param swapData Data used in processing */ function _processRewards(SwapData[] calldata swapData) internal override virtual { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimRewards(swapData); uint128 collectedAmount = _sellRewards(rewards, swapData); if (collectedAmount > 0) { strategy.pendingDepositReward += collectedAmount; } } /* ========== INTERNAL FUNCTIONS ========== */ /** * @notice Process fast withdrawal rewards * @param shares Amount of shares * @param swapData Values used for swapping the rewards * @return withdrawalRewards Withdrawal rewards */ function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) { Strategy storage strategy = strategies[self]; Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData); withdrawalRewards += _sellRewards(rewards, swapData); if (strategy.pendingDepositReward > 0) { uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares); if (fastWithdrawCompound > 0) { strategy.pendingDepositReward -= fastWithdrawCompound; withdrawalRewards += fastWithdrawCompound; } } } /** * @notice Sell rewards to the underlying token * @param rewards Rewards to sell * @param swapData Values used for swapping the rewards * @return collectedAmount Collected underlying amount */ function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) { for (uint256 i = 0; i < rewards.length; i++) { // add compound amount from current batch to the fast withdraw if (rewards[i].amount > 0) { uint128 compoundAmount = SafeCast.toUint128( _approveAndSwap( rewards[i].token, underlying, rewards[i].amount, swapData[i] ) ); // add to pending reward collectedAmount += compoundAmount; } } } /** * @notice Get reward claim amount for `shares` * @param shares Amount of shares * @param rewardAmount Total reward amount * @return rewardAmount Amount of reward for the shares */ function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) { // for do hard work claim everything if (shares == type(uint128).max) { return SafeCast.toUint128(rewardAmount); } else { // for fast withdrawal claim calculate user withdraw amount return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares); } } /* ========== VIRTUAL FUNCTIONS ========== */ function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.11; import "../MultipleRewardStrategy.sol"; import "../../external/interfaces/idle-finance/IIdleToken.sol"; /** * @notice Idle strategy implementation */ contract IdleStrategy is MultipleRewardStrategy { using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ /// @notice Idle token contract IIdleToken public immutable idleToken; /// @notice One idle token shares amount uint256 public immutable oneShare; /* ========== CONSTRUCTOR ========== */ /** * @notice Set initial values * @param _idleToken Idle token contract * @param _underlying Underlying asset */ constructor( IIdleToken _idleToken, IERC20 _underlying ) BaseStrategy(_underlying, 0, 1, 1, 1, true, false) { require(address(_idleToken) != address(0), "IdleStrategy::constructor: Token address cannot be 0"); idleToken = _idleToken; oneShare = 10 ** uint256(_idleToken.decimals()); } /* ========== VIEWS ========== */ /** * @notice Get strategy balance * @return strategyBalance Strategy balance in strategy underlying tokens */ function getStrategyBalance() public view override returns(uint128) { uint256 idleTokenBalance = idleToken.balanceOf(address(this)); return SafeCast.toUint128(_getIdleTokenValue(idleTokenBalance)); } /* ========== OVERRIDDEN FUNCTIONS ========== */ /** * @notice Dynamically return reward slippage length * @dev Reward slippage lenght corresponds with amount of reward tokens a strategy provides */ function _getRewardSlippageSlots() internal view override returns(uint256) { return idleToken.getGovTokens().length; } /** * @notice Deposit to Idle (mint idle tokens) * @param amount Amount to deposit * @param slippages Slippages array * @return Minted idle amount */ function _deposit(uint128 amount, uint256[] memory slippages) internal override returns(uint128) { (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]); require(isDeposit, "IdleStrategy::_deposit: Withdraw slippage provided"); // deposit underlying underlying.safeApprove(address(idleToken), amount); // NOTE: Middle Flag is unused so can be anything uint256 mintedIdleAmount = idleToken.mintIdleToken( amount, true, address(this) ); _resetAllowance(underlying, address(idleToken)); require( mintedIdleAmount >= slippage, "IdleStrategy::_deposit: Insufficient Idle Amount Minted" ); return SafeCast.toUint128(_getIdleTokenValue(mintedIdleAmount)); } /** * @notice Withdraw from the Idle strategy * @param shares Amount of shares to withdraw * @param slippages Slippage values * @return undelyingWithdrawn Withdrawn underlying recieved amount */ function _withdraw(uint128 shares, uint256[] memory slippages) internal override returns(uint128) { (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]); require(!isDeposit, "IdleStrategy::_withdraw: Deposit slippage provided"); uint256 idleTokensTotal = idleToken.balanceOf(address(this)); uint256 redeemIdleAmount = (idleTokensTotal * shares) / strategies[self].totalShares; // withdraw idle tokens from vault uint256 undelyingBefore = underlying.balanceOf(address(this)); idleToken.redeemIdleToken(redeemIdleAmount); uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore; require( undelyingWithdrawn >= slippage, "IdleStrategy::_withdraw: Insufficient withdrawn amount" ); return SafeCast.toUint128(undelyingWithdrawn); } /** * @notice Emergency withdraw all the balance from the idle strategy */ function _emergencyWithdraw(address, uint256[] calldata) internal override { idleToken.redeemIdleToken(idleToken.balanceOf(address(this))); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @notice Get idle token value for the given token amount * @param idleAmount Idle token amount * @return Token value for given amount */ function _getIdleTokenValue(uint256 idleAmount) private view returns(uint256) { if (idleAmount == 0) return 0; return (idleAmount * idleToken.tokenPriceWithFee(address(this))) / oneShare; } /** * @notice Claim all idle governance reward tokens * @dev Force claiming tokens on every strategy interaction * @param shares amount of shares to claim for * @param _swapData Swap values, representing paths to swap the tokens to underlying * @return rewards Claimed reward tokens */ function _claimMultipleRewards(uint128 shares, SwapData[] calldata _swapData) internal override returns(Reward[] memory rewards) { address[] memory rewardTokens = idleToken.getGovTokens(); SwapData[] memory swapData = _swapData; if (swapData.length == 0) { // if no slippages provided we just loop over the rewards to save them swapData = new SwapData[](rewardTokens.length); } else { // init rewards array, to compound them rewards = new Reward[](rewardTokens.length); } uint256[] memory newRewardTokenAmounts = _claimStrategyRewards(rewardTokens); Strategy storage strategy = strategies[self]; for (uint256 i = 0; i < rewardTokens.length; i++) { if (swapData[i].slippage > 0) { uint256 rewardTokenAmount = newRewardTokenAmounts[i] + strategy.pendingRewards[rewardTokens[i]]; if (rewardTokenAmount > 0) { uint256 claimedAmount = _getRewardClaimAmount(shares, rewardTokenAmount); if (rewardTokenAmount > claimedAmount) { // if we don't swap all the tokens (fast withdraw), save the rest uint256 rewardAmountLeft = rewardTokenAmount - claimedAmount; strategy.pendingRewards[rewardTokens[i]] = rewardAmountLeft; } else if (rewardTokenAmount > newRewardTokenAmounts[i]) { // if reward amount is more than new rewards, we reset pendng to 0, otherwise it was 0 already strategy.pendingRewards[rewardTokens[i]] = 0; } rewards[i] = Reward(claimedAmount, IERC20(rewardTokens[i])); } } else if (newRewardTokenAmounts[i] > 0) { strategy.pendingRewards[rewardTokens[i]] += newRewardTokenAmounts[i]; } } } /** * @notice Claim strategy rewards * @param rewardTokens Tokens to claim * @return Reward token amounts */ function _claimStrategyRewards(address[] memory rewardTokens) private returns(uint256[] memory) { uint256[] memory rewardTokenAmountsBefore = _getRewardTokenAmounts(rewardTokens); // claim idleToken.redeemIdleToken(0); uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length); // calculate reward token amounts for (uint256 i = 0; i < rewardTokenAmountsBefore.length; i++) { rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this)) - rewardTokenAmountsBefore[i]; } return rewardTokenAmounts; } /** * @notice Get reward token amounts * @param rewardTokens Reward token address array * @return Reward token amounts */ function _getRewardTokenAmounts(address[] memory rewardTokens) private view returns(uint256[] memory) { uint256[] memory rewardTokenAmounts = new uint[](rewardTokens.length); for (uint256 i = 0; i < rewardTokenAmounts.length; i++) { rewardTokenAmounts[i] = IERC20(rewardTokens[i]).balanceOf(address(this)); } return rewardTokenAmounts; } }
Deposit to Idle (mint idle tokens) amount Amount to deposit slippages Slippages array return Minted idle amount/ deposit underlying NOTE: Middle Flag is unused so can be anything
function _deposit(uint128 amount, uint256[] memory slippages) internal override returns(uint128) { (bool isDeposit, uint256 slippage) = _getSlippageAction(slippages[0]); require(isDeposit, "IdleStrategy::_deposit: Withdraw slippage provided"); underlying.safeApprove(address(idleToken), amount); uint256 mintedIdleAmount = idleToken.mintIdleToken( amount, true, address(this) ); _resetAllowance(underlying, address(idleToken)); require( mintedIdleAmount >= slippage, "IdleStrategy::_deposit: Insufficient Idle Amount Minted" ); return SafeCast.toUint128(_getIdleTokenValue(mintedIdleAmount)); }
1,489,471
//Address: 0xd223e8aed64bf8f2031e1c7b97bf391f1bf75451 //Contract name: PetitionFactory //Balance: 0.002 Ether //Verification Date: 5/31/2018 //Transacion Count: 5 // CODE STARTS HERE pragma solidity 0.4.21; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* ____ _ _ _ _ _ | _ \ ___| |_(_) |_(_) ___ _ __ (_) ___ | |_) / _ \ __| | __| |/ _ \| '_ \ | |/ _ \ | __/ __/ |_| | |_| | (_) | | | |_| | (_) | |_| \___|\__|_|\__|_|\___/|_| |_(_)_|\___/ */ contract PetitionFactory is Ownable { using SafeMath for uint; event NewPetition(uint petitionId, string name, string message, address creator, uint signaturesNeeded, bool featured, uint featuredExpires, uint totalSignatures, uint created, string connectingHash, uint advertisingBudget); event NewPetitionSigner(uint petitionSignerId, uint petitionId, address petitionSignerAddress, uint signed); event NewPetitionShareholder(uint PetitionShareholderId, address PetitionShareholderAddress, uint shares, uint sharesListedForSale, uint lastDividend); event DividendClaim(uint divId, uint PetitionShareholderId, uint amt, uint time, address userAddress); event NewShareholderListing(uint shareholderListingId, uint petitionShareholderId, uint sharesForSale, uint price, bool sold); struct Petition { string name; string message; address creator; uint signaturesNeeded; bool featured; uint featuredExpires; uint totalSignatures; uint created; string connectingHash; uint advertisingBudget; // an easy way for people to donate to the petition cause. We will use this budget for CPC, CPM text and banner ads around petition.io } struct PetitionSigner { uint petitionId; address petitionSignerAddress; uint signed; } struct PetitionShareholder { address PetitionShareholderAddress; uint shares; uint sharesListedForSale; // prevent being able to double list shares for sale uint lastDividend; } struct DividendHistory { uint PetitionShareholderId; uint amt; uint time; address userAddress; } struct ShareholderListing { uint petitionShareholderId; uint sharesForSale; uint price; bool sold; } Petition[] public petitions; PetitionSigner[] public petitionsigners; mapping(address => mapping(uint => uint)) ownerPetitionSignerArrayCreated; mapping(address => mapping(uint => uint)) petitionSignerMap; PetitionShareholder[] public PetitionShareholders; mapping(address => uint) ownerPetitionShareholderArrayCreated; mapping(address => uint) PetitionShareholderMap; DividendHistory[] public divs; ShareholderListing[] public listings; uint createPetitionFee = 1000000000000000; // 0.001 ETH uint featurePetitionFee = 100000000000000000; // 0.1 ETH uint featuredLength = 604800; // 1 week /********************************* */ // shareholder details //uint petitionIoShares = 1000000; // 1,000,000 (20%) of shares given to Petition.io Inc. This is needed so Petition.io Inc can collect 20% of the fees to keep the lights on and continually improve the platform uint sharesSold = 0; uint maxShares = 5000000; // 5,000,000 shares exist // initial price per share from Petition.io (until all shares are sold). But can also be listed and sold p2p on our marketplace at the price set by shareholder uint initialPricePerShare = 5000000000000000; // 0.005 ETH -> // notice of bonuses: // 10 ETH + get a 10% bonus // 50 ETH + get a 20% bonus // 100 ETH + get a 30% bonus // 500 ETH + get a 40% bonus // 1000 ETH + get a 50% bonus uint initialOwnerSharesClaimed = 0; // owner can only claim their 1,000,000 shares once address ownerShareAddress; uint dividendCooldown = 604800; // 1 week uint peerToPeerMarketplaceTransactionFee = 100; // 1% (1 / 100 = 0.01, 2 / 100 = 0.02, etc) uint dividendPoolStarts = 0; uint dividendPoolEnds = 0; uint claimableDividendPool = 0; // (from the last dividendCooldown time pool) uint claimedThisPool = 0; uint currentDividendPool = 0; // (from this dividendCooldown pool) uint availableForWithdraw = 0; /********************************* */ // shareholder functions function invest() payable public { require(sharesSold < maxShares); // calc how many shares uint numberOfShares = SafeMath.div(msg.value, initialPricePerShare); // example is 1 ETH (1000000000000000000) / 0.01 ETH (10000000000000000) = 100 shares // calc bonus uint numberOfSharesBonus; uint numberOfSharesBonusOne; uint numberOfSharesBonusTwo; if (msg.value >= 1000000000000000000000) { // 1000 ETH numberOfSharesBonus = SafeMath.div(numberOfShares, 2); // 50% numberOfShares = SafeMath.add(numberOfShares, numberOfSharesBonus); } else if (msg.value >= 500000000000000000000) { // 500 ETH numberOfSharesBonusOne = SafeMath.div(numberOfShares, 5); // 20% numberOfSharesBonusTwo = SafeMath.div(numberOfShares, 5); // 20% numberOfShares = numberOfShares + numberOfSharesBonusOne + numberOfSharesBonusTwo; // 40% } else if (msg.value >= 100000000000000000000) { // 100 ETH numberOfSharesBonusOne = SafeMath.div(numberOfShares, 5); // 20% numberOfSharesBonusTwo = SafeMath.div(numberOfShares, 10); // 10% numberOfShares = numberOfShares + numberOfSharesBonusOne + numberOfSharesBonusTwo; // 30% } else if (msg.value >= 50000000000000000000) { // 50 ETH numberOfSharesBonus = SafeMath.div(numberOfShares, 5); // 20% numberOfShares = numberOfShares + numberOfSharesBonus; // 20% } else if (msg.value >= 10000000000000000000) { // 10 ETH numberOfSharesBonus = SafeMath.div(numberOfShares, 10); // 10% numberOfShares = numberOfShares + numberOfSharesBonus; // 10% } require((numberOfShares + sharesSold) < maxShares); if (ownerPetitionShareholderArrayCreated[msg.sender] == 0) { // new investor uint id = PetitionShareholders.push(PetitionShareholder(msg.sender, numberOfShares, 0, now)) - 1; emit NewPetitionShareholder(id, msg.sender, numberOfShares, 0, now); PetitionShareholderMap[msg.sender] = id; ownerPetitionShareholderArrayCreated[msg.sender] = 1; sharesSold = sharesSold + numberOfShares; availableForWithdraw = availableForWithdraw + msg.value; } else { // add to amount PetitionShareholders[PetitionShareholderMap[msg.sender]].shares = PetitionShareholders[PetitionShareholderMap[msg.sender]].shares + numberOfShares; sharesSold = sharesSold + numberOfShares; availableForWithdraw = availableForWithdraw + msg.value; } // new div pool? endDividendPool(); } function viewSharesSold() public view returns(uint) { return sharesSold; } function viewMaxShares() public view returns(uint) { return maxShares; } function viewPetitionShareholderWithAddress(address _investorAddress) view public returns (uint, address, uint, uint) { require (ownerPetitionShareholderArrayCreated[_investorAddress] > 0); PetitionShareholder storage investors = PetitionShareholders[PetitionShareholderMap[_investorAddress]]; return (PetitionShareholderMap[_investorAddress], investors.PetitionShareholderAddress, investors.shares, investors.lastDividend); } function viewPetitionShareholder(uint _PetitionShareholderId) view public returns (uint, address, uint, uint) { PetitionShareholder storage investors = PetitionShareholders[_PetitionShareholderId]; return (_PetitionShareholderId, investors.PetitionShareholderAddress, investors.shares, investors.lastDividend); } /********************************* */ // dividend functions function endDividendPool() public { // we do if instead of require so we can call it throughout the smart contract. This way if someone signs, creates a petition, etc. It can ding to the next dividend pool. if (now > dividendPoolEnds) { // unclaimed dividends go to admin available availableForWithdraw = availableForWithdraw + (claimableDividendPool - claimedThisPool); // current div pool to claimable div pool claimableDividendPool = currentDividendPool; claimedThisPool = 0; // reset current div pool currentDividendPool = 0; // start new pool period dividendPoolStarts = now; dividendPoolEnds = (now + dividendCooldown); } } function collectDividend() payable public { require (ownerPetitionShareholderArrayCreated[msg.sender] > 0); require ((PetitionShareholders[PetitionShareholderMap[msg.sender]].lastDividend + dividendCooldown) < now); require (claimableDividendPool > 0); // calc amount uint divAmt = claimableDividendPool / (sharesSold / PetitionShareholders[PetitionShareholderMap[msg.sender]].shares); claimedThisPool = claimedThisPool + divAmt; // PetitionShareholders[PetitionShareholderMap[msg.sender]].lastDividend = now; // the actual ETH transfer PetitionShareholders[PetitionShareholderMap[msg.sender]].PetitionShareholderAddress.transfer(divAmt); uint id = divs.push(DividendHistory(PetitionShareholderMap[msg.sender], divAmt, now, PetitionShareholders[PetitionShareholderMap[msg.sender]].PetitionShareholderAddress)) - 1; emit DividendClaim(id, PetitionShareholderMap[msg.sender], divAmt, now, PetitionShareholders[PetitionShareholderMap[msg.sender]].PetitionShareholderAddress); } function viewInvestorDividendHistory(uint _divId) public view returns(uint, uint, uint, uint, address) { return(_divId, divs[_divId].PetitionShareholderId, divs[_divId].amt, divs[_divId].time, divs[_divId].userAddress); } function viewInvestorDividendPool() public view returns(uint) { return currentDividendPool; } function viewClaimableInvestorDividendPool() public view returns(uint) { return claimableDividendPool; } function viewClaimedThisPool() public view returns(uint) { return claimedThisPool; } function viewLastClaimedDividend(address _address) public view returns(uint) { return PetitionShareholders[PetitionShareholderMap[_address]].lastDividend; } function ViewDividendPoolEnds() public view returns(uint) { return dividendPoolEnds; } function viewDividendCooldown() public view returns(uint) { return dividendCooldown; } // transfer shares function transferShares(uint _amount, address _to) public { require(ownerPetitionShareholderArrayCreated[msg.sender] > 0); require((PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale) >= _amount); // give to receiver if (ownerPetitionShareholderArrayCreated[_to] == 0) { // new investor uint id = PetitionShareholders.push(PetitionShareholder(_to, _amount, 0, now)) - 1; emit NewPetitionShareholder(id, _to, _amount, 0, now); PetitionShareholderMap[_to] = id; ownerPetitionShareholderArrayCreated[_to] = 1; } else { // add to amount PetitionShareholders[PetitionShareholderMap[_to]].shares = PetitionShareholders[PetitionShareholderMap[_to]].shares + _amount; } // take from sender PetitionShareholders[PetitionShareholderMap[msg.sender]].shares = PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - _amount; PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale = PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale - _amount; // new div pool? endDividendPool(); } // p2p share listing, selling and buying function listSharesForSale(uint _amount, uint _price) public { require(ownerPetitionShareholderArrayCreated[msg.sender] > 0); require((PetitionShareholders[PetitionShareholderMap[msg.sender]].shares - PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale) >= _amount); PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale = PetitionShareholders[PetitionShareholderMap[msg.sender]].sharesListedForSale + _amount; uint id = listings.push(ShareholderListing(PetitionShareholderMap[msg.sender], _amount, _price, false)) - 1; emit NewShareholderListing(id, PetitionShareholderMap[msg.sender], _amount, _price, false); // new div pool? endDividendPool(); } function viewShareholderListing(uint _shareholderListingId)view public returns (uint, uint, uint, uint, bool) { ShareholderListing storage listing = listings[_shareholderListingId]; return (_shareholderListingId, listing.petitionShareholderId, listing.sharesForSale, listing.price, listing.sold); } function removeShareholderListing(uint _shareholderListingId) public { ShareholderListing storage listing = listings[_shareholderListingId]; require(PetitionShareholderMap[msg.sender] == listing.petitionShareholderId); PetitionShareholders[listing.petitionShareholderId].sharesListedForSale = PetitionShareholders[listing.petitionShareholderId].sharesListedForSale - listing.sharesForSale; delete listings[_shareholderListingId]; // new div pool? endDividendPool(); } function buySharesFromListing(uint _shareholderListingId) payable public { ShareholderListing storage listing = listings[_shareholderListingId]; require(msg.value >= listing.price); require(listing.sold == false); require(listing.sharesForSale > 0); // give to buyer if (ownerPetitionShareholderArrayCreated[msg.sender] == 0) { // new investor uint id = PetitionShareholders.push(PetitionShareholder(msg.sender, listing.sharesForSale, 0, now)) - 1; emit NewPetitionShareholder(id, msg.sender, listing.sharesForSale, 0, now); PetitionShareholderMap[msg.sender] = id; ownerPetitionShareholderArrayCreated[msg.sender] = 1; } else { // add to amount PetitionShareholders[PetitionShareholderMap[msg.sender]].shares = PetitionShareholders[PetitionShareholderMap[msg.sender]].shares + listing.sharesForSale; } listing.sold = true; // take from seller PetitionShareholders[listing.petitionShareholderId].shares = PetitionShareholders[listing.petitionShareholderId].shares - listing.sharesForSale; PetitionShareholders[listing.petitionShareholderId].sharesListedForSale = PetitionShareholders[listing.petitionShareholderId].sharesListedForSale - listing.sharesForSale; // 1% fee uint calcFee = SafeMath.div(msg.value, peerToPeerMarketplaceTransactionFee); cutToInvestorsDividendPool(calcFee); // transfer funds to seller uint toSeller = SafeMath.sub(msg.value, calcFee); PetitionShareholders[listing.petitionShareholderId].PetitionShareholderAddress.transfer(toSeller); // new div pool? endDividendPool(); } /********************************* */ // petition functions function createPetition(string _name, string _message, uint _signaturesNeeded, bool _featured, string _connectingHash) payable public { require(msg.value >= createPetitionFee); uint featuredExpires = 0; uint totalPaid = createPetitionFee; if (_featured) { require(msg.value >= (createPetitionFee + featurePetitionFee)); featuredExpires = now + featuredLength; totalPaid = totalPaid + featurePetitionFee; } ///////////// // cut to shareholders dividend pool: cutToInvestorsDividendPool(totalPaid); ////////// uint id = petitions.push(Petition(_name, _message, msg.sender, _signaturesNeeded, _featured, featuredExpires, 0, now, _connectingHash, 0)) - 1; emit NewPetition(id, _name, _message, msg.sender, _signaturesNeeded, _featured, featuredExpires, 0, now, _connectingHash, 0); } function renewFeatured(uint _petitionId) payable public { require(msg.value >= featurePetitionFee); uint featuredExpires = 0; if (now > petitions[_petitionId].featuredExpires) { featuredExpires = now + featuredLength; }else { featuredExpires = petitions[_petitionId].featuredExpires + featuredLength; } petitions[_petitionId].featuredExpires = featuredExpires; ///////////// // cut to shareholders dividend pool: cutToInvestorsDividendPool(msg.value); } function viewPetition(uint _petitionId) view public returns (uint, string, string, address, uint, bool, uint, uint, uint, string, uint) { Petition storage petition = petitions[_petitionId]; return (_petitionId, petition.name, petition.message, petition.creator, petition.signaturesNeeded, petition.featured, petition.featuredExpires, petition.totalSignatures, petition.created, petition.connectingHash, petition.advertisingBudget); } function viewPetitionSignerWithAddress(address _ownerAddress, uint _petitionId) view public returns (uint, uint, address, uint) { require (ownerPetitionSignerArrayCreated[_ownerAddress][_petitionId] > 0); PetitionSigner storage signers = petitionsigners[petitionSignerMap[_ownerAddress][_petitionId]]; return (petitionSignerMap[_ownerAddress][_petitionId], signers.petitionId, signers.petitionSignerAddress, signers.signed); } function viewPetitionSigner(uint _petitionSignerId) view public returns (uint, uint, address, uint) { PetitionSigner storage signers = petitionsigners[_petitionSignerId]; return (_petitionSignerId, signers.petitionId, signers.petitionSignerAddress, signers.signed); } function advertisingDeposit (uint _petitionId) payable public { petitions[_petitionId].advertisingBudget = SafeMath.add(petitions[_petitionId].advertisingBudget, msg.value); ///////////// // cut to shareholders dividend pool -> since its advertising we can cut 100% of the msg.value to everyone cutToInvestorsDividendPool(msg.value); } function cutToInvestorsDividendPool(uint totalPaid) internal { // // removed this because as petition.io we still have to claim owned shares % worth from the dividendpool. // calc cut for Petition.io //uint firstDiv = SafeMath.div(PetitionShareholders[PetitionShareholderMap[ownerShareAddress]].shares, sharesSold); //uint petitionIoDivAmt = SafeMath.mul(totalPaid, firstDiv); //availableForWithdraw = availableForWithdraw + petitionIoDivAmt; // calc for shareholders //uint divAmt = SafeMath.sub(totalPaid, petitionIoDivAmt); // add to investors dividend pool //currentDividendPool = SafeMath.add(currentDividendPool, divAmt); currentDividendPool = SafeMath.add(currentDividendPool, totalPaid); // new div pool? endDividendPool(); } function advertisingUse (uint _petitionId, uint amount) public { require(petitions[_petitionId].creator == msg.sender); require(petitions[_petitionId].advertisingBudget >= amount); // (fills out advertising information on website and funds it here) petitions[_petitionId].advertisingBudget = petitions[_petitionId].advertisingBudget - amount; } /********************************* */ // sign function function sign (uint _petitionId) public { // cant send it to a non existing petition require (keccak256(petitions[_petitionId].name) != keccak256("")); require (ownerPetitionSignerArrayCreated[msg.sender][_petitionId] == 0); //if (ownerPetitionSignerArrayCreated[msg.sender][_petitionId] == 0) { uint id = petitionsigners.push(PetitionSigner(_petitionId, msg.sender, now)) - 1; emit NewPetitionSigner(id, _petitionId, msg.sender, now); petitionSignerMap[msg.sender][_petitionId] = id; ownerPetitionSignerArrayCreated[msg.sender][_petitionId] = 1; petitions[_petitionId].totalSignatures = petitions[_petitionId].totalSignatures + 1; //} // new div pool? endDividendPool(); } /********************************* */ // unsign function function unsign (uint _petitionId) public { require (ownerPetitionSignerArrayCreated[msg.sender][_petitionId] == 1); ownerPetitionSignerArrayCreated[msg.sender][_petitionId] = 0; petitions[_petitionId].totalSignatures = petitions[_petitionId].totalSignatures - 1; delete petitionsigners[petitionSignerMap[msg.sender][_petitionId]]; delete petitionSignerMap[msg.sender][_petitionId]; } /********************************* */ // start admin functions function initialOwnersShares() public onlyOwner(){ require(initialOwnerSharesClaimed == 0); uint numberOfShares = 1000000; uint id = PetitionShareholders.push(PetitionShareholder(msg.sender, numberOfShares, 0, now)) - 1; emit NewPetitionShareholder(id, msg.sender, numberOfShares, 0, now); PetitionShareholderMap[msg.sender] = id; ownerPetitionShareholderArrayCreated[msg.sender] = 1; sharesSold = sharesSold + numberOfShares; ownerShareAddress = msg.sender; // dividend pool dividendPoolStarts = now; dividendPoolEnds = (now + dividendCooldown); initialOwnerSharesClaimed = 1; // owner can only claim the intial 1,000,000 shares once } function companyShares() public view returns(uint){ return PetitionShareholders[PetitionShareholderMap[ownerShareAddress]].shares; } function alterDividendCooldown (uint _dividendCooldown) public onlyOwner() { dividendCooldown = _dividendCooldown; } function spendAdvertising(uint _petitionId, uint amount) public onlyOwner() { require(petitions[_petitionId].advertisingBudget >= amount); petitions[_petitionId].advertisingBudget = petitions[_petitionId].advertisingBudget - amount; } function viewFeaturedLength() public view returns(uint) { return featuredLength; } function alterFeaturedLength (uint _newFeaturedLength) public onlyOwner() { featuredLength = _newFeaturedLength; } function viewInitialPricePerShare() public view returns(uint) { return initialPricePerShare; } function alterInitialPricePerShare (uint _initialPricePerShare) public onlyOwner() { initialPricePerShare = _initialPricePerShare; } function viewCreatePetitionFee() public view returns(uint) { return createPetitionFee; } function alterCreatePetitionFee (uint _createPetitionFee) public onlyOwner() { createPetitionFee = _createPetitionFee; } function alterPeerToPeerMarketplaceTransactionFee (uint _peerToPeerMarketplaceTransactionFee) public onlyOwner() { peerToPeerMarketplaceTransactionFee = _peerToPeerMarketplaceTransactionFee; } function viewPeerToPeerMarketplaceTransactionFee() public view returns(uint) { return peerToPeerMarketplaceTransactionFee; } function viewFeaturePetitionFee() public view returns(uint) { return featurePetitionFee; } function alterFeaturePetitionFee (uint _featurePetitionFee) public onlyOwner() { featurePetitionFee = _featurePetitionFee; } function withdrawFromAmt() public view returns(uint) { return availableForWithdraw; } function withdrawFromContract(address _to, uint _amount) payable external onlyOwner() { require(_amount <= availableForWithdraw); availableForWithdraw = availableForWithdraw - _amount; _to.transfer(_amount); // new div pool? endDividendPool(); } /* NOTE: Instead of adding this function to the smart contract and have the power of deleting a petition (having this power doesnt sound very decentralized), in case of anything inappropriate: Petition.io will instead flag the said petition from showing up on the website. Sure someone can make their own website and link to our smart contract and show all the dirty stuff people will inevitably post.. go for it. function deletePetition(uint _petitionId) public onlyOwner() { delete petitions[_petitionId]; }*/ }
we do if instead of require so we can call it throughout the smart contract. This way if someone signs, creates a petition, etc. It can ding to the next dividend pool.
function endDividendPool() public { if (now > dividendPoolEnds) { availableForWithdraw = availableForWithdraw + (claimableDividendPool - claimedThisPool); claimableDividendPool = currentDividendPool; claimedThisPool = 0; currentDividendPool = 0; dividendPoolStarts = now; dividendPoolEnds = (now + dividendCooldown); } }
14,040,052
//SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; pragma abicoder v2; import "../interfaces/IStake1Vault.sol"; import {ITOS} from "../interfaces/ITOS.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IStake1Storage.sol"; import "../libraries/LibTokenStake1.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./StakeVaultStorage.sol"; /// @title TOS Token's Vault - stores the TOS for the period of time /// @notice A vault is associated with the set of stake contracts. /// Stake contracts can interact with the vault to claim TOS tokens contract Stake1Vault is StakeVaultStorage, IStake1Vault { using SafeMath for uint256; /// @dev event on sale-closed event ClosedSale(); /// @dev event of according to request from(staking contract) the amount of compensation is paid to to. /// @param from the stakeContract address that call claim /// @param to the address that will receive the reward /// @param amount the amount of reward event ClaimedReward(address indexed from, address to, uint256 amount); /// @dev constructor of Stake1Vault constructor() {} /// @dev receive function receive() external payable { revert("cannot receive Ether"); } /// @dev Sets TOS address /// @param _tos TOS address function setTOS(address _tos) external override onlyOwner { require(_tos != address(0), "Stake1Vault: input is zero"); tos = _tos; } /// @dev Change cap of the vault /// @param _cap allocated reward amount function changeCap(uint256 _cap) external override onlyOwner { require(_cap > 0 && cap != _cap, "Stake1Vault: changeCap fails"); cap = _cap; } /// @dev Set Defi Address /// @param _defiAddr DeFi related address function setDefiAddr(address _defiAddr) external override onlyOwner { require( _defiAddr != address(0) && defiAddr != _defiAddr, "Stake1Vault: _defiAddr is zero" ); defiAddr = _defiAddr; } /// @dev If the vault has more money than the reward to give, the owner can withdraw the remaining amount. /// @param _amount the amount of withdrawal function withdrawReward(uint256 _amount) external override onlyOwner { require(saleClosed, "Stake1Vault: didn't end sale"); uint256 rewardAmount = 0; for (uint256 i = 0; i < stakeAddresses.length; i++) { rewardAmount = rewardAmount .add(stakeInfos[stakeAddresses[i]].totalRewardAmount) .sub(stakeInfos[stakeAddresses[i]].claimRewardAmount); } uint256 balanceOf = IERC20(tos).balanceOf(address(this)); require( balanceOf >= rewardAmount.add(_amount), "Stake1Vault: insuffient" ); require( IERC20(tos).transfer(msg.sender, _amount), "Stake1Vault: fail withdrawReward" ); } /// @dev Add stake contract /// @param _name stakeContract's name /// @param stakeContract stakeContract's address /// @param periodBlocks the period that give rewards of stakeContract function addSubVaultOfStake( string memory _name, address stakeContract, uint256 periodBlocks ) external override onlyOwner { require( stakeContract != address(0) && cap > 0 && periodBlocks > 0, "Stake1Vault: addStakerInVault init fails" ); require( block.number < stakeStartBlock, "Stake1Vault: Already started stake" ); require(!saleClosed, "Stake1Vault: closed sale"); require( paytoken == IStake1Storage(stakeContract).paytoken(), "Stake1Vault: Different paytoken" ); LibTokenStake1.StakeInfo storage info = stakeInfos[stakeContract]; require(info.startBlock == 0, "Stake1Vault: Already added"); stakeAddresses.push(stakeContract); uint256 _endBlock = stakeStartBlock.add(periodBlocks); info.name = _name; info.startBlock = stakeStartBlock; info.endBlock = _endBlock; if (stakeEndBlock < _endBlock) stakeEndBlock = _endBlock; orderedEndBlocks.push(stakeEndBlock); } /// @dev Close the sale that can stake by user function closeSale() external override { require(!saleClosed, "Stake1Vault: already closed"); require( cap > 0 && stakeStartBlock > 0 && stakeStartBlock < stakeEndBlock && block.number > stakeStartBlock, "Stake1Vault: Before stakeStartBlock" ); require(stakeAddresses.length > 0, "Stake1Vault: no stakes"); realEndBlock = stakeEndBlock; // check balance, update balance for (uint256 i = 0; i < stakeAddresses.length; i++) { LibTokenStake1.StakeInfo storage stakeInfo = stakeInfos[stakeAddresses[i]]; if (paytoken == address(0)) { stakeInfo.balance = address(uint160(stakeAddresses[i])).balance; } else { uint256 balanceAmount = IERC20(paytoken).balanceOf(stakeAddresses[i]); stakeInfo.balance = balanceAmount; } if (stakeInfo.balance > 0) realEndBlock = stakeInfos[stakeAddresses[i]].endBlock; } blockTotalReward = cap.div(realEndBlock.sub(stakeStartBlock)); uint256 sum = 0; // update total for (uint256 i = 0; i < stakeAddresses.length; i++) { LibTokenStake1.StakeInfo storage totalcheck = stakeInfos[stakeAddresses[i]]; uint256 total = 0; for (uint256 j = 0; j < stakeAddresses.length; j++) { if ( stakeInfos[stakeAddresses[j]].endBlock >= totalcheck.endBlock ) { total = total.add(stakeInfos[stakeAddresses[j]].balance); } } if (totalcheck.endBlock > realEndBlock) { continue; } stakeEndBlockTotal[totalcheck.endBlock] = total; sum = sum.add(total); // reward total uint256 totalReward = 0; for (uint256 k = i; k > 0; k--) { if ( stakeEndBlockTotal[stakeInfos[stakeAddresses[k]].endBlock] > 0 ) { totalReward = totalReward.add( stakeInfos[stakeAddresses[k]] .endBlock .sub(stakeInfos[stakeAddresses[k - 1]].endBlock) .mul(blockTotalReward) .mul(totalcheck.balance) .div( stakeEndBlockTotal[ stakeInfos[stakeAddresses[k]].endBlock ] ) ); } } if ( stakeEndBlockTotal[stakeInfos[stakeAddresses[0]].endBlock] > 0 ) { totalReward = totalReward.add( stakeInfos[stakeAddresses[0]] .endBlock .sub(stakeInfos[stakeAddresses[0]].startBlock) .mul(blockTotalReward) .mul(totalcheck.balance) .div( stakeEndBlockTotal[ stakeInfos[stakeAddresses[0]].endBlock ] ) ); } totalcheck.totalRewardAmount = totalReward; } saleClosed = true; emit ClosedSale(); } /// @dev claim function. /// @dev sender is a staking contract. /// @dev A function that pays the amount(_amount) to _to by the staking contract. /// @dev A function that _to claim the amount(_amount) from the staking contract and gets the tos in the vault. /// @param _to a user that received reward /// @param _amount the receiving amount /// @return true function claim(address _to, uint256 _amount) external override returns (bool) { require( saleClosed && _amount > 0, "Stake1Vault: on sale or need to end the sale" ); uint256 tosBalance = IERC20(tos).balanceOf(address(this)); require(tosBalance >= _amount, "Stake1Vault: not enough balance"); LibTokenStake1.StakeInfo storage stakeInfo = stakeInfos[msg.sender]; require(stakeInfo.startBlock > 0, "Stake1Vault: startBlock zero"); require( stakeInfo.totalRewardAmount > 0, "Stake1Vault: totalRewardAmount is zero" ); require( stakeInfo.totalRewardAmount >= stakeInfo.claimRewardAmount.add(_amount), "Stake1Vault: claim amount exceeds" ); stakeInfo.claimRewardAmount = stakeInfo.claimRewardAmount.add(_amount); require( IERC20(tos).transfer(_to, _amount), "Stake1Vault: TOS transfer fail" ); emit ClaimedReward(msg.sender, _to, _amount); return true; } /// @dev Whether user(to) can receive a reward amount(_amount) /// @param _to a staking contract. /// @param _amount the total reward amount of stakeContract /// @return true function canClaim(address _to, uint256 _amount) external view override returns (bool) { require(saleClosed, "Stake1Vault: on sale or need to end the sale"); uint256 tosBalance = IERC20(tos).balanceOf(address(this)); require(tosBalance >= _amount, "not enough"); LibTokenStake1.StakeInfo storage stakeInfo = stakeInfos[_to]; require(stakeInfo.startBlock > 0, "Stake1Vault: startBlock is zero"); require( stakeInfo.totalRewardAmount > 0, "Stake1Vault: amount is wrong" ); require( stakeInfo.totalRewardAmount >= stakeInfo.claimRewardAmount.add(_amount), "Stake1Vault: amount exceeds" ); return true; } /// @dev Returns Give the TOS balance stored in the vault /// @return the balance of TOS in this vault. function balanceTOSAvailableAmount() external view override returns (uint256) { return IERC20(tos).balanceOf(address(this)); } /// @dev Give all stakeContracts's addresses in this vault /// @return all stakeContracts's addresses function stakeAddressesAll() external view override returns (address[] memory) { return stakeAddresses; } /// @dev Give the ordered end blocks of stakeContracts in this vault /// @return the ordered end blocks function orderedEndBlocksAll() external view override returns (uint256[] memory) { return orderedEndBlocks; } /// @dev Give Total reward amount of stakeContract(_account) /// @return Total reward amount of stakeContract(_account) function totalRewardAmount(address _account) external view override returns (uint256) { return stakeInfos[_account].totalRewardAmount; } /// @dev Give the infomation of this vault /// @return [paytoken,defiAddr], cap, stakeType, [saleStartBlock, stakeStartBlock, stakeEndBlock], blockTotalReward, saleClosed function infos() external view override returns ( address[2] memory, uint256, uint256, uint256[3] memory, uint256, bool ) { return ( [paytoken, defiAddr], cap, stakeType, [saleStartBlock, stakeStartBlock, stakeEndBlock], blockTotalReward, saleClosed ); } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; pragma abicoder v2; import "../libraries/LibTokenStake1.sol"; interface IStake1Vault { /// @dev Sets TOS address /// @param _tos TOS address function setTOS(address _tos) external; /// @dev Change cap of the vault /// @param _cap allocated reward amount function changeCap(uint256 _cap) external; /// @dev Set Defi Address /// @param _defiAddr DeFi related address function setDefiAddr(address _defiAddr) external; /// @dev If the vault has more money than the reward to give, the owner can withdraw the remaining amount. /// @param _amount the amount of withdrawal function withdrawReward(uint256 _amount) external; /// @dev Add stake contract /// @param _name stakeContract's name /// @param stakeContract stakeContract's address /// @param periodBlocks the period that give rewards of stakeContract function addSubVaultOfStake( string memory _name, address stakeContract, uint256 periodBlocks ) external; /// @dev Close the sale that can stake by user function closeSale() external; /// @dev claim function. /// @dev sender is a staking contract. /// @dev A function that pays the amount(_amount) to _to by the staking contract. /// @dev A function that _to claim the amount(_amount) from the staking contract and gets the TOS in the vault. /// @param _to a user that received reward /// @param _amount the receiving amount /// @return true function claim(address _to, uint256 _amount) external returns (bool); /// @dev Whether user(to) can receive a reward amount(_amount) /// @param _to a staking contract. /// @param _amount the total reward amount of stakeContract /// @return true function canClaim(address _to, uint256 _amount) external view returns (bool); /// @dev Give the infomation of this vault /// @return paytoken, cap, saleStartBlock, stakeStartBlock, stakeEndBlock, blockTotalReward, saleClosed function infos() external view returns ( address[2] memory, uint256, uint256, uint256[3] memory, uint256, bool ); /// @dev Returns Give the TOS balance stored in the vault /// @return the balance of TOS in this vault. function balanceTOSAvailableAmount() external view returns (uint256); /// @dev Give Total reward amount of stakeContract(_account) /// @return Total reward amount of stakeContract(_account) function totalRewardAmount(address _account) external view returns (uint256); /// @dev Give all stakeContracts's addresses in this vault /// @return all stakeContracts's addresses function stakeAddressesAll() external view returns (address[] memory); /// @dev Give the ordered end blocks of stakeContracts in this vault /// @return the ordered end blocks function orderedEndBlocksAll() external view returns (uint256[] memory); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; interface ITOS { /// @dev Issue a token. /// @param to who takes the issue /// @param amount the amount to issue function mint(address to, uint256 amount) external returns (bool); // @dev burn a token. /// @param from Whose tokens are burned /// @param amount the amount to burn function burn(address from, uint256 amount) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address owner) external view returns (uint256); /// @dev Authorizes the owner's token to be used by the spender as much as the value. /// @dev The signature must have the owner's signature. /// @param owner the token's owner /// @param spender the account that spend owner's token /// @param value the amount to be approve to spend /// @param deadline the deadline that valid the owner's signature /// @param v the owner's signature - v /// @param r the owner's signature - r /// @param s the owner's signature - s function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @dev verify the signature /// @param owner the token's owner /// @param spender the account that spend owner's token /// @param value the amount to be approve to spend /// @param deadline the deadline that valid the owner's signature /// @param _nounce the _nounce /// @param sigR the owner's signature - r /// @param sigS the owner's signature - s /// @param sigV the owner's signature - v function verify( address owner, address spender, uint256 value, uint256 deadline, uint256 _nounce, bytes32 sigR, bytes32 sigS, uint8 sigV ) external view returns (bool); /// @dev the hash of Permit /// @param owner the token's owner /// @param spender the account that spend owner's token /// @param value the amount to be approve to spend /// @param deadline the deadline that valid the owner's signature /// @param _nounce the _nounce function hashPermit( address owner, address spender, uint256 value, uint256 deadline, uint256 _nounce ) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; interface IStake1Storage { /// @dev reward token : TOS function token() external view returns (address); /// @dev registry function stakeRegistry() external view returns (address); /// @dev paytoken is the token that the user stakes. ( if paytoken is ether, paytoken is address(0) ) function paytoken() external view returns (address); /// @dev A vault that holds TOS rewards. function vault() external view returns (address); /// @dev the start block for sale. function saleStartBlock() external view returns (uint256); /// @dev the staking start block, once staking starts, users can no longer apply for staking. function startBlock() external view returns (uint256); /// @dev the staking end block. function endBlock() external view returns (uint256); //// @dev the total amount claimed function rewardClaimedTotal() external view returns (uint256); /// @dev the total staked amount function totalStakedAmount() external view returns (uint256); /// @dev total stakers function totalStakers() external view returns (uint256); /// @dev user's staked information function getUserStaked(address user) external view returns ( uint256 amount, uint256 claimedBlock, uint256 claimedAmount, uint256 releasedBlock, uint256 releasedAmount, uint256 releasedTOSAmount, bool released ); } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; library LibTokenStake1 { enum DefiStatus { NONE, APPROVE, DEPOSITED, REQUESTWITHDRAW, REQUESTWITHDRAWALL, WITHDRAW, END } struct DefiInfo { string name; address router; address ext1; address ext2; uint256 fee; address routerV2; } struct StakeInfo { string name; uint256 startBlock; uint256 endBlock; uint256 balance; uint256 totalRewardAmount; uint256 claimRewardAmount; } struct StakedAmount { uint256 amount; uint256 claimedBlock; uint256 claimedAmount; uint256 releasedBlock; uint256 releasedAmount; uint256 releasedTOSAmount; bool released; } struct StakedAmountForSTOS { uint256 amount; uint256 startBlock; uint256 periodBlock; uint256 rewardPerBlock; uint256 claimedBlock; uint256 claimedAmount; uint256 releasedBlock; uint256 releasedAmount; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.7.6; //import "../interfaces/IStakeVaultStorage.sol"; import "../libraries/LibTokenStake1.sol"; import "../common/AccessibleCommon.sol"; /// @title the storage of StakeVaultStorage contract StakeVaultStorage is AccessibleCommon { /// @dev reward token : TOS address public tos; /// @dev paytoken is the token that the user stakes. address public paytoken; /// @dev allocated amount of tos uint256 public cap; /// @dev the start block for sale. uint256 public saleStartBlock; /// @dev the staking start block uint256 public stakeStartBlock; /// @dev the staking end block. uint256 public stakeEndBlock; /// @dev the staking real end block. uint256 public realEndBlock; /// @dev reward amount per block uint256 public blockTotalReward; /// @dev sale closed flag bool public saleClosed; /// @dev Operation type of staking amount uint256 public stakeType; /// @dev External contract address used when operating the staking amount address public defiAddr; /// @dev a list of stakeContracts maintained by the vault address[] public stakeAddresses; /// @dev the information of the stake contract mapping(address => LibTokenStake1.StakeInfo) public stakeInfos; /// @dev the end blocks of the stake contracts, which must be in ascending order uint256[] public orderedEndBlocks; /// @dev the total staked amount stored at orderedEndBlock’s end block time mapping(uint256 => uint256) public stakeEndBlockTotal; uint256 private _lock; /// @dev flag for pause proxy bool public pauseProxy; ///@dev for migrate L2 bool public migratedL2; modifier lock() { require(_lock == 0, "Stake1Vault: LOCKED"); _lock = 1; _; _lock = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./AccessRoleCommon.sol"; contract AccessibleCommon is AccessRoleCommon, AccessControl { modifier onlyOwner() { require(isAdmin(msg.sender), "Accessible: Caller is not an admin"); _; } /// @dev add admin /// @param account address to add function addAdmin(address account) public virtual onlyOwner { grantRole(ADMIN_ROLE, account); } /// @dev remove admin /// @param account address to remove function removeAdmin(address account) public virtual onlyOwner { renounceRole(ADMIN_ROLE, account); } /// @dev transfer admin /// @param newAdmin new admin address function transferAdmin(address newAdmin) external virtual onlyOwner { require(newAdmin != address(0), "Accessible: zero address"); require(msg.sender != newAdmin, "Accessible: same admin"); grantRole(ADMIN_ROLE, newAdmin); renounceRole(ADMIN_ROLE, msg.sender); } /// @dev whether admin /// @param account address to check function isAdmin(address account) public view virtual returns (bool) { return hasRole(ADMIN_ROLE, account); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; contract AccessRoleCommon { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); bytes32 public constant MINTER_ROLE = keccak256("MINTER"); bytes32 public constant BURNER_ROLE = keccak256("BURNER"); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Give the ordered end blocks of stakeContracts in this vault return the ordered end blocks
function orderedEndBlocksAll() external view override returns (uint256[] memory) { return orderedEndBlocks; }
9,825,108
./full_match/137/0x971f4c09cb893071dC04C0418B91Dd590262Eca0/sources/project_/contracts/sale/MembershipTokenSale.sol
배열 번호에 해당하는 판매 정보 리턴
function getSaleInfo (uint256 _saleIndex) public view returns (SaleItem memory) { SaleItem memory sale = SaleTokenList[_saleIndex]; return sale; }
4,726,079
// SPDX-License-Identifier: MIT pragma solidity 0.7.3; import "../YakStrategyV2.sol"; import "../interfaces/IPair.sol"; import "../lib/DexLibrary.sol"; /** * @notice Adapter strategy for MasterChef. */ abstract contract MasterChefStrategy is YakStrategyV2 { using SafeMath for uint256; IWAVAX private constant WAVAX = IWAVAX(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); struct StrategySettings { uint256 minTokensToReinvest; uint256 adminFeeBips; uint256 devFeeBips; uint256 reinvestRewardBips; } uint256 public immutable PID; address private stakingContract; address private poolRewardToken; IPair private swapPairPoolReward; address public swapPairExtraReward; address public extraToken; constructor( string memory _name, address _depositToken, address _ecosystemToken, address _poolRewardToken, address _swapPairPoolReward, address _swapPairExtraReward, address _stakingContract, address _timelock, uint256 _pid, StrategySettings memory _strategySettings ) Ownable() { name = _name; depositToken = IERC20(_depositToken); rewardToken = IERC20(_ecosystemToken); PID = _pid; devAddr = 0x2D580F9CF2fB2D09BC411532988F2aFdA4E7BefF; stakingContract = _stakingContract; assignSwapPairSafely(_ecosystemToken, _poolRewardToken, _swapPairPoolReward); _setExtraRewardSwapPair(_swapPairExtraReward); updateMinTokensToReinvest(_strategySettings.minTokensToReinvest); updateAdminFee(_strategySettings.adminFeeBips); updateDevFee(_strategySettings.devFeeBips); updateReinvestReward(_strategySettings.reinvestRewardBips); updateDepositsEnabled(true); transferOwnership(_timelock); emit Reinvest(0, 0); } /** * @notice Initialization helper for Pair deposit tokens * @dev Checks that selected Pairs are valid for trading reward tokens * @dev Assigns values to IPair(swapPairToken0) and IPair(swapPairToken1) */ function assignSwapPairSafely( address _ecosystemToken, address _poolRewardToken, address _swapPairPoolReward ) private { if (_poolRewardToken != _ecosystemToken) { if (_poolRewardToken == IPair(_swapPairPoolReward).token0()) { require( IPair(_swapPairPoolReward).token1() == _ecosystemToken, "Swap pair 'swapPairPoolReward' does not contain ecosystem token" ); } else if (_poolRewardToken == IPair(_swapPairPoolReward).token1()) { require( IPair(_swapPairPoolReward).token0() == _ecosystemToken, "Swap pair 'swapPairPoolReward' does not contain ecosystem token" ); } else { revert("Swap pair 'swapPairPoolReward' does not contain pool reward token"); } } poolRewardToken = _poolRewardToken; swapPairPoolReward = IPair(_swapPairPoolReward); } /** * @notice Approve tokens for use in Strategy * @dev Deprecated; approvals should be handled in context of staking */ function setAllowances() public override onlyOwner { revert("setAllowances::deprecated"); } function setExtraRewardSwapPair(address _extraTokenSwapPair) external onlyDev { _setExtraRewardSwapPair(_extraTokenSwapPair); } function _setExtraRewardSwapPair(address _extraTokenSwapPair) internal { if (_extraTokenSwapPair > address(0)) { if (IPair(_extraTokenSwapPair).token0() == address(rewardToken)) { extraToken = IPair(_extraTokenSwapPair).token1(); } else { extraToken = IPair(_extraTokenSwapPair).token0(); } swapPairExtraReward = _extraTokenSwapPair; } else { swapPairExtraReward = address(0); extraToken = address(0); } } /** * @notice Deposit tokens to receive receipt tokens * @param amount Amount of tokens to deposit */ function deposit(uint256 amount) external override { _deposit(msg.sender, amount); } /** * @notice Deposit using Permit * @param amount Amount of tokens to deposit * @param deadline 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 depositWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { depositToken.permit(msg.sender, address(this), amount, deadline, v, r, s); _deposit(msg.sender, amount); } function depositFor(address account, uint256 amount) external override { _deposit(account, amount); } function _deposit(address account, uint256 amount) internal { require(DEPOSITS_ENABLED == true, "MasterChefStrategyV1::_deposit"); if (MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST > 0) { ( uint256 poolTokenAmount, uint256 extraTokenAmount, uint256 rewardTokenBalance, uint256 estimatedTotalReward ) = _checkReward(); if (estimatedTotalReward > MAX_TOKENS_TO_DEPOSIT_WITHOUT_REINVEST) { _reinvest(rewardTokenBalance, poolTokenAmount, extraTokenAmount); } } require(depositToken.transferFrom(msg.sender, address(this), amount), "MasterChefStrategyV1::transfer failed"); uint256 depositFeeBips = _getDepositFeeBips(PID); uint256 depositFee = amount.mul(depositFeeBips).div(_bip()); _mint(account, getSharesForDepositTokens(amount.sub(depositFee))); _stakeDepositTokens(amount); emit Deposit(account, amount); } function withdraw(uint256 amount) external override { uint256 depositTokenAmount = getDepositTokensForShares(amount); require(depositTokenAmount > 0, "MasterChefStrategyV1::withdraw"); _withdrawDepositTokens(depositTokenAmount); uint256 withdrawFeeBips = _getWithdrawFeeBips(PID); uint256 withdrawFee = depositTokenAmount.mul(withdrawFeeBips).div(_bip()); _safeTransfer(address(depositToken), msg.sender, depositTokenAmount.sub(withdrawFee)); _burn(msg.sender, amount); emit Withdraw(msg.sender, depositTokenAmount); } function _withdrawDepositTokens(uint256 amount) private { _withdrawMasterchef(PID, amount); } function reinvest() external override onlyEOA { ( uint256 poolTokenAmount, uint256 extraTokenAmount, uint256 rewardTokenBalance, uint256 estimatedTotalReward ) = _checkReward(); require(estimatedTotalReward >= MIN_TOKENS_TO_REINVEST, "MasterChefStrategyV1::reinvest"); _reinvest(rewardTokenBalance, poolTokenAmount, extraTokenAmount); } function _convertPoolTokensIntoReward(uint256 poolTokenAmount) private returns (uint256) { if (address(rewardToken) == poolRewardToken) { return poolTokenAmount; } return DexLibrary.swap(poolTokenAmount, address(poolRewardToken), address(rewardToken), swapPairPoolReward); } function _convertExtraTokensIntoReward(uint256 rewardTokenBalance, uint256 extraTokenAmount) internal returns (uint256) { if (extraTokenAmount > 0) { if (swapPairExtraReward > address(0)) { return DexLibrary.swap(extraTokenAmount, extraToken, address(rewardToken), IPair(swapPairExtraReward)); } uint256 avaxBalance = address(this).balance; if (avaxBalance > 0) { WAVAX.deposit{value: avaxBalance}(); } return WAVAX.balanceOf(address(this)).sub(rewardTokenBalance); } return 0; } /** * @notice Reinvest rewards from staking contract to deposit tokens * @dev Reverts if the expected amount of tokens are not returned from `MasterChef` */ function _reinvest( uint256 rewardTokenBalance, uint256 poolTokenAmount, uint256 extraTokenAmount ) private { _getRewards(PID); uint256 amount = rewardTokenBalance.add(_convertPoolTokensIntoReward(poolTokenAmount)); amount.add(_convertExtraTokensIntoReward(rewardTokenBalance, extraTokenAmount)); uint256 devFee = amount.mul(DEV_FEE_BIPS).div(BIPS_DIVISOR); if (devFee > 0) { _safeTransfer(address(rewardToken), devAddr, devFee); } uint256 reinvestFee = amount.mul(REINVEST_REWARD_BIPS).div(BIPS_DIVISOR); if (reinvestFee > 0) { _safeTransfer(address(rewardToken), msg.sender, reinvestFee); } uint256 depositTokenAmount = _convertRewardTokenToDepositToken(amount.sub(devFee).sub(reinvestFee)); _stakeDepositTokens(depositTokenAmount); emit Reinvest(totalDeposits(), totalSupply); } function _stakeDepositTokens(uint256 amount) private { require(amount > 0, "MasterChefStrategyV1::_stakeDepositTokens"); _depositMasterchef(PID, amount); } /** * @notice Safely transfer using an anonymous ERC20 token * @dev Requires token to return true on transfer * @param token address * @param to recipient address * @param value amount */ function _safeTransfer( address token, address to, uint256 value ) private { require(IERC20(token).transfer(to, value), "MasterChefStrategyV1::TRANSFER_FROM_FAILED"); } function _checkReward() internal view returns ( uint256 _poolTokenAmount, uint256 _extraTokenAmount, uint256 _rewardTokenBalance, uint256 _estimatedTotalReward ) { uint256 poolTokenBalance = IERC20(poolRewardToken).balanceOf(address(this)); (uint256 pendingPoolTokenAmount, uint256 pendingExtraTokenAmount, address extraTokenAddress) = _pendingRewards( PID, address(this) ); uint256 poolTokenAmount = poolTokenBalance.add(pendingPoolTokenAmount); uint256 pendingRewardTokenAmount = poolRewardToken != address(rewardToken) ? DexLibrary.estimateConversionThroughPair( poolTokenAmount, poolRewardToken, address(rewardToken), swapPairPoolReward ) : pendingPoolTokenAmount; uint256 pendingExtraTokenRewardAmount = 0; if (extraTokenAddress > address(0)) { if (extraTokenAddress == address(WAVAX)) { pendingExtraTokenRewardAmount = pendingExtraTokenAmount; } else if (swapPairExtraReward > address(0)) { pendingExtraTokenAmount = pendingExtraTokenAmount.add(IERC20(extraToken).balanceOf(address(this))); pendingExtraTokenRewardAmount = DexLibrary.estimateConversionThroughPair( pendingExtraTokenAmount, extraTokenAddress, address(rewardToken), IPair(swapPairExtraReward) ); } } uint256 rewardTokenBalance = rewardToken.balanceOf(address(this)).add(pendingExtraTokenRewardAmount); uint256 estimatedTotalReward = rewardTokenBalance.add(pendingRewardTokenAmount); return (poolTokenAmount, pendingExtraTokenAmount, rewardTokenBalance, estimatedTotalReward); } function checkReward() public view override returns (uint256) { (, , , uint256 estimatedTotalReward) = _checkReward(); return estimatedTotalReward; } /** * @notice Estimate recoverable balance after withdraw fee * @return deposit tokens after withdraw fee */ function estimateDeployedBalance() external view override returns (uint256) { uint256 depositBalance = totalDeposits(); uint256 withdrawFeeBips = _getWithdrawFeeBips(PID); uint256 withdrawFee = depositBalance.mul(withdrawFeeBips).div(_bip()); return depositBalance.sub(withdrawFee); } function totalDeposits() public view override returns (uint256) { uint256 depositBalance = _getDepositBalance(PID, address(this)); return depositBalance; } function rescueDeployedFunds(uint256 minReturnAmountAccepted, bool disableDeposits) external override onlyOwner { uint256 balanceBefore = depositToken.balanceOf(address(this)); _emergencyWithdraw(PID); uint256 balanceAfter = depositToken.balanceOf(address(this)); require( balanceAfter.sub(balanceBefore) >= minReturnAmountAccepted, "MasterChefStrategyV1::rescueDeployedFunds" ); emit Reinvest(totalDeposits(), totalSupply); if (DEPOSITS_ENABLED == true && disableDeposits == true) { updateDepositsEnabled(false); } } /* VIRTUAL */ function _convertRewardTokenToDepositToken(uint256 fromAmount) internal virtual returns (uint256 toAmount); function _depositMasterchef(uint256 pid, uint256 amount) internal virtual; function _withdrawMasterchef(uint256 pid, uint256 amount) internal virtual; function _emergencyWithdraw(uint256 pid) internal virtual; function _getRewards(uint256 pid) internal virtual; function _pendingRewards(uint256 pid, address user) internal view virtual returns ( uint256 poolTokenAmount, uint256 extraTokenAmount, address extraTokenAddress ); function _getDepositBalance(uint256 pid, address user) internal view virtual returns (uint256 amount); function _getDepositFeeBips(uint256 pid) internal view virtual returns (uint256); function _getWithdrawFeeBips(uint256 pid) internal view virtual returns (uint256); function _bip() internal view virtual returns (uint256); }
Initialization helper for Pair deposit tokens Checks that selected Pairs are valid for trading reward tokens Assigns values to IPair(swapPairToken0) and IPair(swapPairToken1)/
function assignSwapPairSafely( address _ecosystemToken, address _poolRewardToken, address _swapPairPoolReward ) private { if (_poolRewardToken != _ecosystemToken) { if (_poolRewardToken == IPair(_swapPairPoolReward).token0()) { require( IPair(_swapPairPoolReward).token1() == _ecosystemToken, "Swap pair 'swapPairPoolReward' does not contain ecosystem token" ); require( IPair(_swapPairPoolReward).token0() == _ecosystemToken, "Swap pair 'swapPairPoolReward' does not contain ecosystem token" ); revert("Swap pair 'swapPairPoolReward' does not contain pool reward token"); } } poolRewardToken = _poolRewardToken; swapPairPoolReward = IPair(_swapPairPoolReward); }
1,039,622
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title SushiSwap Double Incentive. * @dev Decentralized Exchange. */ import { TokenInterface } from "../../common/interfaces.sol"; import { Helpers } from "./helpers.sol"; import { Events } from "./events.sol"; abstract contract SushipswapIncentiveResolver is Helpers, Events { /** * @dev deposit LP token to masterChef * @notice deposit LP token to masterChef * @param token1 token1 of LP token * @param token2 token2 of LP token * @param amount amount of LP token * @param getId ID to retrieve amount * @param setId ID stores Pool ID * @param data the metadata struct */ function deposit( address token1, address token2, uint256 amount, uint256 getId, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); amount = getUint(getId, amount); if ( data.poolId == uint256(-1) || data.version == 0 || data.lpToken == address(0) ) { data = _getPoolId(token1, token2); } setUint(setId, data.poolId); require(data.poolId != uint256(-1), "pool-does-not-exist"); TokenInterface lpToken = TokenInterface(data.lpToken); lpToken.approve(address(masterChef), amount); _deposit(data, amount); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, amount ); } /** * @dev withdraw LP token from masterChef * @notice withdraw LP token from masterChef * @param token1 token1 of LP token * @param token2 token2 of LP token * @param amount amount of LP token * @param getId ID to retrieve amount * @param setId ID stores Pool ID * @param data the metadata struct */ function withdraw( address token1, address token2, uint256 amount, uint256 getId, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); amount = getUint(getId, amount); if (data.poolId == uint256(-1) || data.version == 0) { data = _getPoolId(token1, token2); } setUint(setId, amount); require(data.poolId != uint256(-1), "pool-does-not-exist"); _withdraw(data, amount); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, amount ); } /** * @dev harvest from masterChef * @notice harvest from masterChef * @param token1 token1 deposited of LP token * @param token2 token2 deposited LP token * @param setId ID stores Pool ID * @param data the metadata struct */ function harvest( address token1, address token2, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); if (data.poolId == uint256(-1) || data.version == 0) { data = _getPoolId(token1, token2); } setUint(setId, data.poolId); require(data.poolId != uint256(-1), "pool-does-not-exist"); (, uint256 rewardsAmount) = _getUserInfo(data); if (data.version == 2) _harvest(data); else _withdraw(data, 0); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, rewardsAmount ); } /** * @dev withdraw LP token and harvest from masterChef * @notice withdraw LP token and harvest from masterChef * @param token1 token1 of LP token * @param token2 token2 of LP token * @param amount amount of LP token * @param getId ID to retrieve amount * @param setId ID stores Pool ID * @param data the metadata struct */ function withdrawAndHarvest( address token1, address token2, uint256 amount, uint256 getId, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); amount = getUint(getId, amount); if (data.poolId == uint256(-1) || data.version == 0) { data = _getPoolId(token1, token2); } setUint(setId, data.poolId); require(data.poolId != uint256(-1), "pool-does-not-exist"); (, uint256 rewardsAmount) = _getUserInfo(data); _withdrawAndHarvest(data, amount); _eventName = "LogWithdrawAndHarvest(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, amount, rewardsAmount ); } /** * @dev emergency withdraw from masterChef * @notice emergency withdraw from masterChef * @param token1 token1 deposited of LP token * @param token2 token2 deposited LP token * @param setId ID stores Pool ID * @param data the metadata struct */ function emergencyWithdraw( address token1, address token2, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); if (data.poolId == uint256(-1) || data.version == 0) { data = _getPoolId(token1, token2); } uint256 currentBal = _balance(token1, token2); require(data.poolId != uint256(-1), "pool-does-not-exist"); (uint256 lpAmount, uint256 rewardsAmount) = _getUserInfo(data); _emergencyWithdraw(data); uint256 finalBal = _balance(token1, token2); setUint(setId, uint256(currentBal - finalBal)); _eventName = "LogEmergencyWithdraw(address,address,uint256,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, lpAmount, rewardsAmount ); } } contract ConnectV2SushiswapIncentive is SushipswapIncentiveResolver { string public constant name = "SushipswapIncentive-v1.1"; }
harvest from masterChef harvest from masterChef token1 token1 deposited of LP token token2 token2 deposited LP token setId ID stores Pool ID data the metadata struct/
function harvest( address token1, address token2, uint256 setId, Metadata memory data ) external payable returns (string memory _eventName, bytes memory _eventParam) { token1 = changeEthAddrToWethAddr(token1); token2 = changeEthAddrToWethAddr(token2); if (data.poolId == uint256(-1) || data.version == 0) { data = _getPoolId(token1, token2); } setUint(setId, data.poolId); require(data.poolId != uint256(-1), "pool-does-not-exist"); (, uint256 rewardsAmount) = _getUserInfo(data); if (data.version == 2) _harvest(data); else _withdraw(data, 0); _eventName = "LogDeposit(address,address,uint256,uint256,uint256)"; _eventParam = abi.encode( token1, token2, data.poolId, data.version, rewardsAmount ); }
944,591
pragma solidity ^0.4.17; // Decentralized autonomous lottery contract DAL { // ... } struct Bet { // Bet amount uint256 value; // Guessed numbers uint32 betHash; // Future block to validate the bet uint32 validateBlock; } // Mapping to store bet against an user. mapping(address => Bet) bets; function play(uint _hash) payable public { //... } require(msg.value <= 1 ether && msg.value >= 0.1 ether); uint24 bethash = uint24(_hash); uint256 blockNumber = block.number + 3; bets[msg.sender] = Bet({ value: msg.value, betHash: uint32(bethash), validateBlock: uint32(blockNumber) }); // Event declaration event LogBet( address indexed player, uint256 bethash, uint256 blocknumber, uint256 betsize ); // Event log emit LogBet( msg.sender, uint(bethash), blockNumber, msg.value ); function () payable external { play(uint(keccak256(msg.sender, block.number))); } pragma solidity^0.4.23; contract DAL { // Data structure to store the bet details struct Bet { uint256 value; uint32 betHash; uint32 validateBlock; } // Mapping of user and their bet mapping(address => Bet) bets; // Event to track each bet event LogBet( address indexed player, uint256 bethash, uint256 blocknumber, uint256 betsize ); /** * @dev Function to place a bet * @param _hash Number guessed */ function play(uint _hash) payable public { require(msg.value <= 1 ether && msg.value >= 0.1 ether); uint24 bethash = uint24(_hash); uint256 blockNumber = block.number + 3; bets[msg.sender] = Bet({ value: msg.value, betHash: uint32(bethash), validateBlock: uint32(blockNumber) }); emit LogBet( msg.sender, uint(bethash), blockNumber, msg.value ); } /** * @dev Fallback function which acts as a shortcut * to the token buying process */ function () payable external { play(uint(keccak256(msg.sender, block.number))); } }
Fallback function which acts as a shortcut to the token buying process/
function () payable external { play(uint(keccak256(msg.sender, block.number))); }
6,367,627
./full_match/1/0xe0651907B99e349198a4F7fc96430a809b9AeD83/sources/contracts/Raffle/ERC1155PrizeWrapper.sol
operator The address which initiated the transfer (i.e. msg.sender) from The address which previously owned the token id The ID of the token being transferred value The amount of tokens being transferred data Additional data with no specified format return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed/
(i.e. 0xf23a6e61, or its own function selector). function onERC1155Received(address operator, address from, uint256 id, uint256 value, bytes calldata data) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
9,695,643
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title ERC20 compliant implementation of custom token. /// @author Robi Markac /// @notice This contract can be used as POC governance token /// @dev Functions are implemented in the spirit of POC thus it should be adjusted before deploying to main net contract RobiToken is ERC20 { /// @notice BalanceCheckpoint struct determines balance at certain block height struct BalanceCheckpoint { uint blockHeight; uint balance; } /// @dev _balanceCheckpoints mapping maps user address to his balance checkpoints mapping(address => BalanceCheckpoint[]) private _balanceCheckpoints; /// @notice Construct contract by providing ERC20 params (token name and symbol) and initial supply of token /// @param initialSupply The initial token supply /// @param name A token name /// @param symbol A token symbol constructor(uint256 initialSupply, string memory name, string memory symbol) ERC20(name, symbol) { _mint(msg.sender, initialSupply); } /// @notice Retrieve balance checkpoints for specific address /// @param _address Users address for which balance checkpoints are being requested /// @return BalanceCheckpoint[] Array of users balance checkpoints function getBalanceCheckpoints(address _address) public view returns (BalanceCheckpoint[] memory) { return _balanceCheckpoints[_address]; } /// @notice Retrieve balance checkpoint for specific address /// @dev Returned BalanceCheckpoint will be set to 0 values if none exist /// @param _address Users address for which latest balance checkpoint is requested /// @return BalanceCheckpoint Latest users balance checkpoint or zero initialized BalanceCheckpoint function getLatestBalanceCheckpoint(address _address) public view returns (BalanceCheckpoint memory) { BalanceCheckpoint[] memory checkpointsArray = _balanceCheckpoints[_address]; if (checkpointsArray.length > 0) { return checkpointsArray[checkpointsArray.length - 1]; } else { return BalanceCheckpoint(0, 0); } } /// @notice Retrieve balance of specific address at specific block height /// @dev This function can be computing intensive so consider caching value /// @param _address Users address for which balance is requested /// @param _blockHeight Block height at which users balance is requested /// @return uint Users balance at provided block height function getBalanceAtBlockHeight(address _address, uint _blockHeight) external view returns (uint) { BalanceCheckpoint[] storage checkpoints = _balanceCheckpoints[_address]; // iterate from back to front seeking last checkpoint before voteStart for (uint i = checkpoints.length; i > 0; i--) { // when you find first checkpoint before voteStart if (checkpoints[i-1].blockHeight < _blockHeight) { return checkpoints[i-1].balance; } } return 0; } /// @notice Override of _afterTokenTransfer with custom added balance checkpoint logic /// @dev Override of _afterTokenTransfer is required by Solidity function _afterTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { super._afterTokenTransfer(from, to, amount); // checkpoint sender and receiver balance at this block height _balanceCheckpoints[from].push(BalanceCheckpoint(block.number, balanceOf(from))); _balanceCheckpoints[to].push(BalanceCheckpoint(block.number, balanceOf(to))); } /// @notice Testing function to mint contracts tokens to specific address /// @dev This function should be removed or constrained with role check modifier for production /// @param amount uint256 number representing amount to mint to msg.sender function mintMe(uint256 amount) public { return _mint(msg.sender, amount); } /// @notice Override of _mint ERC20 function /// @dev Override of _mint is required by Solidity function _mint(address to, uint256 amount) internal override(ERC20) { super._mint(to, amount); } /// @notice Override of _burn ERC20 function /// @dev Override of _burn is required by Solidity function _burn(address account, uint256 amount) internal override(ERC20) { super._burn(account, amount); } }
Retrieve balance of specific address at specific block height This function can be computing intensive so consider caching value _address Users address for which balance is requested _blockHeight Block height at which users balance is requested return uint Users balance at provided block height iterate from back to front seeking last checkpoint before voteStart when you find first checkpoint before voteStart
function getBalanceAtBlockHeight(address _address, uint _blockHeight) external view returns (uint) { BalanceCheckpoint[] storage checkpoints = _balanceCheckpoints[_address]; for (uint i = checkpoints.length; i > 0; i--) { if (checkpoints[i-1].blockHeight < _blockHeight) { return checkpoints[i-1].balance; } } return 0; }
12,742,944
./partial_match/4/0xBB4D9ab065E8d3d46e28F762057960F58E2c5F1F/sources/StoboxToken.sol
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "New owner cannot be current owner"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
8,579,196
// SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.8.3; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./library/Bytes32Library.sol"; import "./library/StringLibrary.sol"; import "./interfaces/IPortfolio.sol"; import "./interfaces/ITradePairs.sol"; /** * @author "DEXALOT TEAM" * @title "The Exchange contract is the main entry point to DEXALOT Decentralized Exchange Trading." * * @dev Start up order: * @dev 1. Deploy contracts: Exchange, Portfolio, OrderBooks, TradePairs * @dev 2. Call addTradePairs on Exchange * @dev 3. Call setPortfolio and setTradePairs on Exchange * @dev 4. Change ownership of contracts as per below * @dev 5. Call addToken on Exchange to add supported ERC20 tokens to Portfolio * * @dev "During deployment the ownerships of contracts are changed so they become as follows once DEXALOT is fully deployed:" * @dev "Exchange is owned by proxyAdmin." * @dev "Portfolio contract is owned by exchange contract." * @dev "TradePairs contract is owned by exchange contract." * @dev "OrderBooks contract is owned by TradePairs contract." * @dev "Only tradepairs can internally call addExecution and adjustAvailable functions." * @dev "Only valid trader accounts can call deposit and withdraw functions for their own accounts." */ contract Exchange is Initializable, AccessControlEnumerableUpgradeable { using SafeERC20Upgradeable for IERC20MetadataUpgradeable; using StringLibrary for string; using Bytes32Library for bytes32; // version bytes32 constant public VERSION = bytes32('1.1.0'); // map and array of all trading pairs on DEXALOT ITradePairs private tradePairs; // portfolio reference IPortfolio private portfolio; event PortfolioSet(IPortfolio _oldPortfolio, IPortfolio _newPortfolio); event TradePairsSet(ITradePairs _oldTradePairs, ITradePairs _newTradePairs); function initialize() public initializer { __AccessControl_init(); // intitialize the admins _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // set deployment account to have DEFAULT_ADMIN_ROLE } function owner() public view returns(address) { return getRoleMember(DEFAULT_ADMIN_ROLE, 0); } function addAdmin(address _address) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-01"); grantRole(DEFAULT_ADMIN_ROLE, _address); } function removeAdmin(address _address) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-02"); require(getRoleMemberCount(DEFAULT_ADMIN_ROLE)>1, "E-ALOA-01"); revokeRole(DEFAULT_ADMIN_ROLE, _address); } function isAdmin(address _address) public view returns(bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } // FRONTEND FUNCTION TO GET A LIST OF TRADE PAIRS function getTradePairs() public view returns(bytes32[] memory) { return tradePairs.getTradePairs(); } // DEPLOYMENT ACCOUNT FUNCTION TO UPDATE FEE RATES FOR DEPOSIT AND WITHDRAW function updateTransferFeeRate(uint _rate, IPortfolio.Tx _rateType) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-03"); portfolio.updateTransferFeeRate(_rate, _rateType); } // DEPLOYMENT ACCOUNT FUNCTION TO UPDATE FEE RATE EXECUTIONS function updateRate(bytes32 _tradePair, uint _rate, ITradePairs.RateType _rateType) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-04"); tradePairs.updateRate(_tradePair, _rate, _rateType); } // DEPLOYMENT ACCOUNT FUNCTION TO GET MAKER FEE RATE function getMakerRate(bytes32 _tradePairId) public view returns (uint) { return tradePairs.getMakerRate(_tradePairId); } // DEPLOYMENT ACCOUNT FUNCTION TO GET TAKER FEE RATE function getTakerRate(bytes32 _tradePairId) public view returns (uint) { return tradePairs.getTakerRate(_tradePairId); } // DEPLOYMENT ACCOUNT FUNCTION TO SET PORTFOLIO FOR THE EXCHANGE function setPortfolio(IPortfolio _portfolio) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-05"); emit PortfolioSet(portfolio, _portfolio); portfolio = _portfolio; } // FRONTEND FUNCTION TO GET PORTFOLIO function getPortfolio() public view returns(IPortfolio) { return portfolio; } // DEPLOYMENT ACCOUNT FUNCTION TO SET TRADEPAIRS FOR THE EXCHANGE function setTradePairs(ITradePairs _tradePairs) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-06"); emit TradePairsSet(tradePairs, _tradePairs); tradePairs = _tradePairs; } // FRONTEND FUNCTION TO GET TRADEPAIRS function getTradePairsAddr() public view returns(ITradePairs) { return tradePairs; } // DEPLOYMENT ACCOUNT FUNCTION TO ADD A NEW TRADEPAIR function addTradePair(bytes32 _tradePairId, address _baseAssetAddr, uint8 _baseDisplayDecimals, address _quoteAssetAddr, uint8 _quoteDisplayDecimals, uint _minTradeAmount, uint _maxTradeAmount) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-07"); (bytes32 _baseAssetSymbol, uint8 _baseAssetDecimals) = getAssetMeta(_baseAssetAddr); (bytes32 _quoteAssetSymbol, uint8 _quoteAssetDecimals) = getAssetMeta(_quoteAssetAddr); // check if base asset is native AVAX, if not it is ERC20 and add it if (_baseAssetSymbol != bytes32("AVAX")) { portfolio.addToken(_baseAssetSymbol, IERC20MetadataUpgradeable(_baseAssetAddr)); } // check if quote asset is native AVAX, if not it is ERC20 and add it if (_quoteAssetSymbol != bytes32("AVAX")) { portfolio.addToken(_quoteAssetSymbol, IERC20MetadataUpgradeable(_quoteAssetAddr)); } tradePairs.addTradePair(_tradePairId, _baseAssetSymbol, _baseAssetDecimals, _baseDisplayDecimals, _quoteAssetSymbol, _quoteAssetDecimals, _quoteDisplayDecimals, _minTradeAmount, _maxTradeAmount); } function getAssetMeta(address _assetAddr) private view returns (bytes32 _symbol, uint8 _decimals) { if (_assetAddr == address(0)) { return (bytes32("AVAX"), 18); } else { IERC20MetadataUpgradeable _asset = IERC20MetadataUpgradeable(_assetAddr); return (StringLibrary.stringToBytes32(_asset.symbol()), _asset.decimals()); } } // DEPLOYMENT ACCOUNT FUNCTION TO PAUSE AND UNPAUSE THE PORTFOLIO CONTRACT - AFFECTS ALL DEPOSIT AND WITHDRAW FUNCTIONS function pausePortfolio(bool _paused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-08"); if (_paused) { portfolio.pause(); } else { portfolio.unpause(); } } // DEPLOYMENT ACCOUNT FUNCTION TO DISABLE ONLY DEPOSIT FUNCTIONS function pauseDeposit(bool _paused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-09"); portfolio.pauseDeposit(_paused); } // DEPLOYMENT ACCOUNT FUNCTION TO PAUSE AND UNPAUSE THE TRADEPAIRS CONTRACT // AFFECTS BOTH ADDORDER AND CANCELORDER FUNCTIONS FOR ALL TRADE PAIRS function pauseTrading(bool _tradingPaused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-10"); if (_tradingPaused) { tradePairs.pause(); } else { tradePairs.unpause(); } } // DEPLOYMENT ACCOUNT FUNCTION TO PAUSE AND UNPAUSE THE TRADEPAIRS CONTRACT // AFFECTS BOTH ADDORDER AND CANCELORDER FUNCTIONS FOR A SELECTED TRADE PAIR function pauseTradePair(bytes32 _tradePairId, bool _tradePairPaused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-11"); tradePairs.pauseTradePair(_tradePairId, _tradePairPaused); } // DEPLOYMENT ACCOUNT FUNCTION TO DISABLE ONLY ADDORDER FUNCTION FOR A TRADEPAIR function pauseAddOrder(bytes32 _tradePairId, bool _addOrderPaused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-12"); tradePairs.pauseAddOrder(_tradePairId, _addOrderPaused); } // DEPLOYMENT ACCOUNT FUNCTION TO ADD AN ORDER TYPE TO A TRADEPAIR function addOrderType(bytes32 _tradePairId, ITradePairs.Type1 _type) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-13"); tradePairs.addOrderType(_tradePairId, _type); } // DEPLOYMENT ACCOUNT FUNCTION TO REMOVE AN ORDER TYPE FROM A TRADEPAIR function removeOrderType(bytes32 _tradePairId, ITradePairs.Type1 _type) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-14"); tradePairs.removeOrderType(_tradePairId, _type); } // DEPLOYMENT ACCOUNT FUNCTION TO SET MIN TRADE AMOUNT FOR A TRADEPAIR function setMinTradeAmount(bytes32 _tradePairId, uint _minTradeAmount) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-15"); tradePairs.setMinTradeAmount(_tradePairId, _minTradeAmount); } // FRONTEND FUNCTION TO GET MIN TRADE AMOUNT function getMinTradeAmount(bytes32 _tradePairId) public view returns (uint) { return tradePairs.getMinTradeAmount(_tradePairId); } // DEPLOYMENT ACCOUNT FUNCTION TO SET MAX TRADE AMOUNT FOR A TRADEPAIR function setMaxTradeAmount(bytes32 _tradePairId, uint _maxTradeAmount) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-16"); tradePairs.setMaxTradeAmount(_tradePairId, _maxTradeAmount); } // FRONTEND FUNCTION TO GET MAX TRADE AMOUNT function getMaxTradeAmount(bytes32 _tradePairId) public view returns (uint) { return tradePairs.getMaxTradeAmount(_tradePairId); } // FRONTEND FUNCTION TO SET DISPLAY DECIMALS function setDisplayDecimals(bytes32 _tradePairId, uint8 _displayDecimals, bool _isBase) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-17"); tradePairs.setDisplayDecimals(_tradePairId, _displayDecimals, _isBase); } // FRONTEND FUNCTION TO GET DISPLAY DECIMALS function getDisplayDecimals(bytes32 _tradePairId, bool _isBase) public view returns(uint8) { return tradePairs.getDisplayDecimals(_tradePairId, _isBase); } // FRONTEND FUNCTION TO GET DECIMALS function getDecimals(bytes32 _tradePairId, bool _isBase) public view returns(uint8) { return tradePairs.getDecimals(_tradePairId, _isBase); } // FRONTEND FUNCTION TO GET DECIMALS function getSymbol(bytes32 _tradePairId, bool _isBase) public view returns(bytes32) { return tradePairs.getSymbol(_tradePairId, _isBase); } // DEPLOYMENT ACCOUNT FUNCTION TO SET ALLOWED SLIPPAGE PERCENT function setAllowedSlippagePercent(bytes32 _tradePairId, uint8 _allowedSlippagePercent) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-18"); tradePairs.setAllowedSlippagePercent(_tradePairId, _allowedSlippagePercent); } // DEPLOYMENT ACCOUNT FUNCTION TO GET ALLOWED SLIPPAGE PERCENT function getAllowedSlippagePercent(bytes32 _tradePairId) public view returns (uint8) { return tradePairs.getAllowedSlippagePercent(_tradePairId); } // DEPLOYMENT ACCOUNT FUNCTION TO ADD A NEW TOKEN // NEEDS TO BE CALLED ONLY AFTER PORTFOLIO IS SET FOR EXCHANGE AND PORTFOLIO OWNERSHIP IS CHANGED TO EXCHANGE function addToken(bytes32 _symbol, IERC20Upgradeable _token) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-19"); portfolio.addToken(_symbol, _token); } fallback() external {} // utility function to convert string to bytes32 function stringToBytes32(string memory _string) public pure returns (bytes32 result) { return _string.stringToBytes32(); } // utility function to convert bytes32 to string function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { return _bytes32.bytes32ToString(); } }
DEPLOYMENT ACCOUNT FUNCTION TO DISABLE ONLY ADDORDER FUNCTION FOR A TRADEPAIR
function pauseAddOrder(bytes32 _tradePairId, bool _addOrderPaused) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "E-OACC-12"); tradePairs.pauseAddOrder(_tradePairId, _addOrderPaused); }
1,840,876
pragma solidity 0.4.24; import "@aragon/os/contracts/apps/UnsafeAragonApp.sol"; import "@aragon/os/contracts/common/EtherTokenConstant.sol"; import "@aragon/os/contracts/common/IsContract.sol"; import "@aragon/os/contracts/common/SafeERC20.sol"; import "@aragon/os/contracts/lib/math/SafeMath.sol"; import "@aragon/os/contracts/lib/token/ERC20.sol"; import "./IContinuousToken.sol"; import "./Vault.sol"; import "@ablack/fundraising-bancor-formula/contracts/BancorFormula.sol"; import "@ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol"; contract MarketMaker is EtherTokenConstant, IsContract, UnsafeAragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10**18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; IContinuousToken public bondedToken; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary(address indexed beneficiary); event UpdateFormula(address indexed formula); event UpdateFees(uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch(uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage ); event CancelBatch(uint256 indexed id, address indexed collateral); event AddCollateralToken( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken(address indexed collateral); event UpdateCollateralToken( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open(); event OpenBuyOrder( address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value ); event OpenSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder(address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder( address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value ); event ClaimCancelledBuyOrder( address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value ); event ClaimCancelledSellOrder( address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount ); event UpdatePricing( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _bondedToken The address of the bonded token * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IKernel _kernel, IAragonFundraisingController _controller, IContinuousToken _bondedToken, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_kernel), ERROR_CONTRACT_IS_EOA); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_bondedToken), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); controller = _controller; bondedToken = _bondedToken; formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; setKernel(_kernel); } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder( address _buyer, address _collateral, uint256 _value ) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder( address _seller, address _collateral, uint256 _amount ) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder( address _buyer, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder( address _seller, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder( address _buyer, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder( address _seller, uint256 _batchId, address _collateral ) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns ( bool, uint256, uint256, uint32, uint256 ) { Collateral storage collateral = collaterals[_collateral]; return ( collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage ); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns ( bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256 ) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM( uint256 _supply, uint256 _balance, uint32 _reserveRatio ) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM( uint256 _supply, uint256 _balance, uint32 _reserveRatio ) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _collateralValueIsValid( address _buyer, address _collateral, uint256 _value, uint256 _msgValue ) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return (_msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && bondedToken.balanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer( uint256 _batchId, address _collateral, address _user ) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller( uint256 _batchId, address _collateral, address _user ) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid( Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage ) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid( Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage ) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = bondedToken.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch( batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula ); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller .balanceOf(address(reserve), _collateral) .add(collaterals[_collateral].virtualBalance) .sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub( batch.totalSellReturn ); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder( address _buyer, address _collateral, uint256 _value ) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add( batch.totalSellReturn ); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder( address _seller, address _collateral, uint256 _amount ) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds bondedToken.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add( batch.totalSellReturn ); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder( address _buyer, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); bondedToken.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder( address _seller, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder( address _buyer, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder( address _seller, uint256 _batchId, address _collateral ) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); bondedToken.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing( Batch storage batch, uint256 _batchId, address _collateral ) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn( batch.supply, batch.balance, batch.reserveRatio, remainingSell ); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn( batch.supply, batch.balance, batch.reserveRatio, remainingBuy ); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing( _batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function _transfer( address _from, address _to, address _collateralToken, uint256 _amount ) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } }
Open a buy order worth `@tokenAmount(_collateral, _value)` _buyer The address of the buyer _collateral The address of the collateral token to be spent _value The amount of collateral token to be spent/
function openBuyOrder( address _buyer, address _collateral, uint256 _value ) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); }
5,455,286
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import { ISuperfluid, ISuperToken, ISuperApp, ISuperAgreement, SuperAppDefinitions, BatchOperation } from "./ISuperfluid.sol"; // When you're ready to leave Remix, change imports to follow this pattern: // "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import { IConstantFlowAgreementV1 } from "./IConstantFlowAgreementV1.sol"; import { SuperAppBase } from "./SuperAppBase.sol"; import { Simple777Recipient } from "./Simple777Recipient.sol"; import { SafeMath } from "./SafeMath.sol"; struct traderDetails { address provider; address validator; int96 lastBuyPrice; // the price of the A token to the B token } enum Action { CREATE, UPDATE, DELETE } contract SuperExchange is Simple777Recipient, SuperAppBase { using SafeMath for int96; ISuperfluid private _host; // host IConstantFlowAgreementV1 private _cfa; // the stored constant flow agreement class address ISuperToken private _acceptedTokenA; // accepted token A ISuperToken private _acceptedTokenB; // accepted token B int96 constant fullStreamPercentage = 10000; int96 constant providerzFeePercentage = 30; int96 constant insuranceFeePercentage = 40; int96 constant protocolsFeePercentage = 1; mapping (address => traderDetails) public traders; mapping (uint32 => address) public providerz; mapping (address => address[]) public providerUsers; uint32 public providersNumber; constructor( ISuperfluid host, IConstantFlowAgreementV1 cfa, ISuperToken acceptedTokenA, ISuperToken acceptedTokenB ) Simple777Recipient(address(acceptedTokenA), address(acceptedTokenB)) { assert(address(host) != address(0)); assert(address(cfa) != address(0)); assert(address(acceptedTokenA) != address(0)); assert(address(acceptedTokenB) != address(0)); _host = host; _cfa = cfa; _acceptedTokenA = acceptedTokenA; _acceptedTokenB = acceptedTokenB; uint256 configWord = SuperAppDefinitions.APP_LEVEL_FINAL; _host.registerApp(configWord); } /******************************************************************* *********************GENERAL UTILITY FUNCTIONS********************** ********************************************************************/ // modulo function that I will use when deal with price function abs(int96 x) private pure returns (int96) { return x >= 0 ? x : -x; } // function to check if a token belongs to the pool (used mainly by the afterAgreement callbacks to check if a user uses a token that belongs to the pool) function _isAllowedToken(ISuperToken superToken) private view returns (bool) { return address(superToken) == address(_acceptedTokenA) || address(superToken) == address(_acceptedTokenB); } // function to check if a user uses exactly constant flow agreement and not any else (used in the afterAgreement callbacks) function _isCFAv1(address agreementClass) private view returns (bool) { return ISuperAgreement(agreementClass).agreementType() == keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1"); } // function to check if a user is in the providerz list (returns true if the user is a provider) function isInProvidersList(address user) public view returns (bool){ for (uint32 i = 0; i < providersNumber; i++){ if (providerz[i] == user){ return true; } } return false; } // modifier to check if callbacks are called by the host and not anyone else modifier onlyHost() { require(msg.sender == address(_host), "SatisfyFlows: support only one host"); _; } // modifier to check if a token belongs to the pool and an agreement is a constant flow agreement modifier onlyExpected(ISuperToken superToken, address agreementClass) { require(_isAllowedToken(superToken), "SatisfyFlows: not accepted token"); require(_isCFAv1(agreementClass), "SatisfyFlows: only CFAv1 supported"); _; } /******************************************************************* ***********************SUPERX UTILITY FUNCTIONS********************* ********************************************************************/ // for the token passed as a parameter - get another token in the pool function _getAnotherToken(ISuperToken _superToken1) private view returns (ISuperToken _superToken2){ if (_superToken1 == _acceptedTokenA){ _superToken2 = _acceptedTokenB; } else { _superToken2 = _acceptedTokenA; } } // returns a token stream going back from the contract to a provider function _getTokenStreamToProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){ (,stream,,) = _cfa.getFlow(_superToken, address(this), provider); } function _getTokenStreamFromProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){ (,stream,,) = _cfa.getFlow(_superToken, provider, address(this)); } // returns a new bought token stream based on the old streams, sold token stream and the constant product formula x*y = k // or soldTokenStream*BoughtTokenStream = k // or oldSoldTokensStream*oldBoughtTokenStream = newSoldTokenStream*newBoughtTokenStream // (y') = (x*y)/(x') function _getyNew(int96 x, int96 y, int96 xNew) private pure returns (int96 yNew){ yNew = (x*y)/xNew; } // returns the price of a provider function _getProviderPrice(address provider, ISuperToken soldToken) private view returns (int96 providerPrice) { int96 soldStream = _getTokenStreamToProvider(provider, soldToken); int96 boughtStream = _getTokenStreamToProvider(provider, _getAnotherToken(soldToken)); providerPrice = boughtStream*10^18/soldStream; } // get best price provider function _getBestProvider(ISuperToken soldToken) private view returns (address bestProvider) { int96 maxPrice; int96 providerPrice; for (uint32 i = 0; i < providersNumber; i++){ if (providerz[i] == address(0x0)){ continue; } providerPrice = _getProviderPrice(providerz[i], soldToken); if (maxPrice < providerPrice){ maxPrice = providerPrice; bestProvider = providerz[i]; } } } function _getTokenStreamFromUser(ISuperToken superToken, address user) private view returns (int96 stream){ (,stream,,) = _cfa.getFlow(superToken, user, address(this)); } function _getTokenStreamToUser(ISuperToken superToken, address user) private view returns (int96 stream){ (,stream,,) = _cfa.getFlow(superToken, address(this), user); } /******************************************************************* ***************************CRUD FUNCTIONS*************************** ********************************************************************/ // add a new user to the mappings function _addUser(address userToAdd, address providerOfUser, int96 price) private { providerUsers[providerOfUser].push(userToAdd); traders[userToAdd] = traderDetails({provider: providerOfUser, validator: userToAdd, lastBuyPrice: price}); } // delete a user from the storage function _deleteUser(address userToDelete) private returns (bool){ address[] storage users = providerUsers[traders[userToDelete].provider]; for (uint i = 0; i < users.length; i++){ if (users[i] == userToDelete){ delete users[i]; return true; } } return false; } // add a new provider to the mappings function _addProvider (address providerToAdd) private { providerz[providersNumber++] = providerToAdd; } // delete a provider and therefore their users from the system function _deleteProvider(address providerToDelete) private returns (bool){ uint32 providersCount = providersNumber; for (uint32 i = 0; i < providersCount; i++){ if (providerz[i] == providerToDelete){ providersNumber--; providerz[i] = providerz[providersNumber]; delete providerz[providersNumber]; _deleteProviderUsers(providerToDelete); return true; } } return false; } function _deleteProviderUsers(address provider) private { address[] storage users = providerUsers[provider]; for (uint j = 0; j < users.length; j++){ delete traders[users[j]]; } delete providerUsers[provider]; } /// @dev doesn't remove users from the mappings, just their streams function _removeProviderUsersStreams(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){ address[] storage users = providerUsers[provider]; newCtx = _ctx; for (uint i = 0; i < users.length; i++){ newCtx = _crudFlow(newCtx, users[i], superToken, 0, Action.DELETE); } } function _createBackStreamsToUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){ newCtx = _ctx; address[] storage users = providerUsers[provider]; int96 userInflow; for (uint i = 0; i < users.length; i++){ userInflow = _getTokenStreamToUser(superToken, users[i]); if (userInflow > 0){ newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.UPDATE); } else { newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.CREATE); } } } function _unsubscribeProviderUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){ newCtx = _removeProviderUsersStreams(_ctx, provider, superToken); newCtx = _createBackStreamsToUsers(newCtx, provider, _getAnotherToken(superToken)); } // function that allows for easily creating/updating/deleting flows function _crudFlow(bytes memory _ctx, address receiver, ISuperToken token, int96 flowRate, Action action) private returns (bytes memory newCtx){ newCtx = _ctx; if (action == Action.CREATE){ (newCtx, ) = _host.callAgreementWithContext( _cfa, abi.encodeWithSelector( _cfa.createFlow.selector, token, receiver, flowRate, new bytes(0) ), "0x", newCtx ); } else if (action == Action.UPDATE){ (newCtx, ) = _host.callAgreementWithContext( _cfa, abi.encodeWithSelector( _cfa.updateFlow.selector, token, receiver, flowRate, new bytes(0) ), "0x", newCtx ); } else { // @dev if inFlowRate is zero, delete outflow. (newCtx, ) = _host.callAgreementWithContext( _cfa, abi.encodeWithSelector( _cfa.deleteFlow.selector, token, address(this), receiver, new bytes(0) // placeholder ), "0x", newCtx ); } } // update streams in accordance to the new streams' values function _updateStreamsToLP(bytes memory _ctx, ISuperToken soldToken, address provider, int96 soldStream, int96 boughtStream) private returns (bytes memory newCtx) { newCtx = _crudFlow(_ctx, provider, soldToken, soldStream, Action.UPDATE); newCtx = _crudFlow(newCtx, provider, _getAnotherToken(soldToken), boughtStream, Action.UPDATE); } // function that creates, updates and deletes stream of the user and updates the Liquidity Pool in accordance to that function _crudTradeStream(bytes memory _ctx, address streamer, ISuperToken soldToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){ newCtx = _ctx; address bestProvider; { int96 insuranceFee; int96 userBoughtTokenStream; ISuperToken boughtToken = _getAnotherToken(soldToken); { int96 providerFee; int96 xNew; int96 yNew; { (,int96 fullStream,,) = _cfa.getFlow(soldToken, streamer, address(this)); // check if no providerz and if so, just stream funds back if (providersNumber == 0){ return _crudFlow(newCtx, streamer, soldToken, fullStream, action); } // look for the best provider if create, update if (action == Action.CREATE || action == Action.UPDATE){ bestProvider = _getBestProvider(soldToken); } // strip full stream from all the fees { int96 diffStream = fullStream - prevInflow; providerFee = diffStream*providerzFeePercentage/fullStreamPercentage; insuranceFee = diffStream*insuranceFeePercentage/fullStreamPercentage; fullStream -= (providerFee + diffStream*protocolsFeePercentage/fullStreamPercentage + insuranceFee); } { // calculate new backstreams for the user's provider int96 x = _getTokenStreamToProvider(bestProvider, soldToken); int96 y = _getTokenStreamToProvider(bestProvider, boughtToken); xNew = x + fullStream; yNew = _getyNew(x, y, xNew); // this is the new bought token amount // calculate new bought token stream for the user userBoughtTokenStream = y - yNew; } } // TODO check if the userBoughtTokenStream can be paid from the provider and if not - stream tokens back // update the streams to the provider newCtx = _updateStreamsToLP(newCtx, soldToken, bestProvider, xNew + providerFee, yNew); } // create/update/delete new stream to the user newCtx = _crudFlow(newCtx, streamer, boughtToken, userBoughtTokenStream + insuranceFee, action); } // update mappings if (action == Action.CREATE){ int96 price = _getProviderPrice(bestProvider, _acceptedTokenA); _addUser(streamer, bestProvider, price); } else if (action == Action.DELETE){ _deleteUser(streamer); } } // function that creates, updates or deletes new liquidity and updates the Liquidity Pool in accordance to that function _crudLiquidityProvider(bytes memory _ctx, address provider, ISuperToken superToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){ newCtx = _ctx; // if create then // create streams of this token and another token back int96 tokenStreamFromProvider = _getTokenStreamFromProvider(provider, superToken); // add provider to the system if (action == Action.CREATE){ _addProvider(provider); } // if update then // check if the new stream is enough to pay users int96 tokenStreamToProvider; if (action == Action.UPDATE){ tokenStreamToProvider = _getTokenStreamToProvider(provider, superToken); } // if not or delete - remove subscribed users if (action == Action.DELETE || tokenStreamFromProvider < prevInflow - tokenStreamToProvider){ // delete their streams newCtx = _unsubscribeProviderUsers(newCtx, provider, superToken); // delete them from a mapping if (action == Action.DELETE){ _deleteProvider(provider); }else{ _deleteProviderUsers(provider); } } // create, update or delete backstream newCtx = _crudFlow(newCtx, provider, superToken, tokenStreamFromProvider, action); } /******************************************************************* *************************SUPERX CALLBACKS*************************** ********************************************************************/ // function name says for herself, but to be precise, the purpose of the function is to execute a logic that could've been in the callbacks if not the error function _getRidOfStackTooDeepError(bytes memory _ctx, bytes memory _cbdata) private returns (bytes memory newCtx){ newCtx = _ctx; int96 prevInflow; address streamer; ISuperToken superToken; Action action; (prevInflow, streamer, superToken, action) = abi.decode(_cbdata, (int96, address, ISuperToken, Action)); { int96 anotherTokenInflowRate; { (,anotherTokenInflowRate,,) = _cfa.getFlow(_getAnotherToken(superToken), streamer, address(this)); // inflow of another token to the contract } if (anotherTokenInflowRate > 0){ newCtx = _crudLiquidityProvider(newCtx, streamer, superToken, prevInflow, action); }else{ newCtx = _crudTradeStream(newCtx, streamer, superToken, prevInflow, action); } } return newCtx; } function beforeAgreementCreated( ISuperToken _superToken, address /*agreementClass*/, bytes32 /*agreementId*/, bytes calldata /*agreementData*/, bytes calldata _ctx ) external view override returns (bytes memory _cbdata) { return abi.encode(int96(0), _host.decodeCtx(_ctx).msgSender, _superToken, Action.CREATE); // 0 - previous stream argument } function afterAgreementCreated( ISuperToken _superToken, address _agreementClass, bytes32, bytes calldata /*_agreementData*/, bytes calldata _cbdata, bytes calldata _ctx ) external override onlyExpected(_superToken, _agreementClass) onlyHost returns (bytes memory newCtx) { return _getRidOfStackTooDeepError(_ctx, _cbdata); } function beforeAgreementUpdated( ISuperToken _superToken, address /*agreementClass*/, bytes32 /*agreementId*/, bytes calldata /*agreementData*/, bytes calldata _ctx ) external view override returns (bytes memory _cbdata) { address streamer = _host.decodeCtx(_ctx).msgSender; (,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this)); return abi.encode(prevInflow, streamer, _superToken, Action.UPDATE); } function afterAgreementUpdated( ISuperToken _superToken, address _agreementClass, bytes32 /* _agreementId */, bytes calldata /*_agreementData*/, bytes calldata _cbdata, bytes calldata _ctx ) external override onlyExpected(_superToken, _agreementClass) onlyHost returns (bytes memory newCtx) { return _getRidOfStackTooDeepError(_ctx, _cbdata); } function beforeAgreementTerminated( ISuperToken _superToken, address /*agreementClass*/, bytes32 /*agreementId*/, bytes calldata _agreementData, bytes calldata /* _ctx */ ) external view override returns (bytes memory _cbdata) { (address streamer,) = abi.decode(_agreementData, (address, address)); (,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this)); return abi.encode(prevInflow, streamer, _superToken, Action.DELETE); } function afterAgreementTerminated( ISuperToken _superToken, address _agreementClass, bytes32 /* _agreementId */, bytes calldata /* _agreementData */, bytes calldata _cbdata, bytes calldata _ctx ) external override onlyHost returns (bytes memory newCtx) { // According to the app basic law, we should never revert in a termination callback if (!_isAllowedToken(_superToken) || !_isCFAv1(_agreementClass)) return _ctx; return _getRidOfStackTooDeepError(_ctx, _cbdata); } function destroy() external { selfdestruct(payable(address(0xCb5Dccc2eF9752575d727E93495eDAD092a7c35E))); } }
returns the price of a provider
function _getProviderPrice(address provider, ISuperToken soldToken) private view returns (int96 providerPrice) { int96 soldStream = _getTokenStreamToProvider(provider, soldToken); int96 boughtStream = _getTokenStreamToProvider(provider, _getAnotherToken(soldToken)); providerPrice = boughtStream*10^18/soldStream; }
1,067,571
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Counters.sol"; import "./NameableCharacter.sol"; import "./AllowedColorsStorage.sol"; import "hardhat/console.sol"; /** * @title NiftyDegen NFT (The OG NFTs of the Nifty League on Ethereum) * @dev Extends NameableCharacter and NiftyLeagueCharacter (ERC721) */ contract NiftyDegen is NameableCharacter { using Counters for Counters.Counter; /// @notice Counter for number of minted characters Counters.Counter public totalSupply; /// @notice Max number of mintable characters uint256 public constant MAX_SUPPLY = 10000; /// @notice Special characters reserved for future giveaways uint256 public constant SPECIAL_CHARACTERS = 100; /// @dev Available traits storage address address internal immutable _storageAddress; /// @dev Mapping trait indexes to pool size of available traits mapping(uint256 => uint256) internal _originalPoolSizes; /// @dev Set if we want to override semi-fomo ramp pricing uint256 private _manualMintPrice; /// @dev Base URI used for token metadata string private _baseTokenUri = ""; /** * @notice Construct the Nifty League NFTs * @param nftlAddress Address of verified Nifty League NFTL contract * @param storageAddress Address of verified Allowed Colors Storage */ constructor(address nftlAddress, address storageAddress) NiftyLeagueCharacter(nftlAddress, "NiftyDegen", "DEGEN") { _storageAddress = storageAddress; } // External functions /** * @notice Validate character traits and purchase a Nifty Degen NFT * @param character Indexed list of character traits * @param head Indexed list of head traits * @param clothing Indexed list of clothing options * @param accessories Indexed list of accessories * @param items Indexed list of items * @dev Order is based on character selector indexes */ function purchase( uint256[5] memory character, uint256[3] memory head, uint256[6] memory clothing, uint256[6] memory accessories, uint256[2] memory items ) external payable whenNotPaused { uint256 currentSupply = totalSupply.current(); require(currentSupply >= 3 || _msgSender() == owner(), "Sale has not started"); require(msg.value == getNFTPrice(), "Ether value incorrect"); _validateTraits(character, head, clothing, accessories, items); uint256 traitCombo = _generateTraitCombo(character, head, clothing, accessories, items); _storeNewCharacter(traitCombo); } /** * @notice Set pool size for each trait index called on deploy * @dev Unable to init mapping at declaration :/ */ function initPoolSizes() external onlyOwner { _originalPoolSizes[5] = 113; _originalPoolSizes[6] = 14; _originalPoolSizes[7] = 63; _originalPoolSizes[8] = 99; _originalPoolSizes[9] = 76; _originalPoolSizes[10] = 41; _originalPoolSizes[11] = 101; _originalPoolSizes[12] = 37; _originalPoolSizes[13] = 12; _originalPoolSizes[14] = 43; _originalPoolSizes[15] = 50; _originalPoolSizes[16] = 10; _originalPoolSizes[17] = 12; _originalPoolSizes[18] = 25; _originalPoolSizes[19] = 37; _originalPoolSizes[20] = 92; _originalPoolSizes[21] = 48; } /** * @notice Fallback to set NFT price to static ether value if necessary * @param newPrice New price to set for remaining character sale * @dev Minimum value of 0.08 ETH for this to be considered in getNFTPrice */ function overrideMintPrice(uint256 newPrice) external onlyOwner { _manualMintPrice = newPrice; } /** * @notice Option to set _baseUri for transfering Heroku to IPFS * @param baseURI New base URI for NFT metadata */ function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenUri = baseURI; } // Public functions /** * @notice Gets current NFT Price based on current supply * @return Current price to mint 1 NFT */ function getNFTPrice() public view returns (uint256) { uint256 currentSupply = totalSupply.current(); require( currentSupply < MAX_SUPPLY - SPECIAL_CHARACTERS || (_msgSender() == owner() && currentSupply < MAX_SUPPLY), "Sale has already ended" ); // 1 - 3 free for core team members, 9901 - 10000 free special community giveaway characters if (currentSupply < 3 || currentSupply >= 9900) return 0; // fallback option to override price floors only if necessary. Minimum value of 0.08 ETH if (_manualMintPrice >= 80000000000000000) return _manualMintPrice; if (currentSupply >= 9500) return 280000000000000000; // 9500 - 9900 0.28 ETH if (currentSupply >= 8500) return 250000000000000000; // 8501 - 9500 0.25 ETH if (currentSupply >= 6500) return 220000000000000000; // 6501 - 8500 0.22 ETH if (currentSupply >= 4500) return 190000000000000000; // 4501 - 6500 0.18 ETH if (currentSupply >= 2500) return 160000000000000000; // 2501 - 4500 0.15 ETH if (currentSupply >= 1000) return 130000000000000000; // 1001 - 2500 0.13 ETH return 100000000000000000; // 4 - 1000 0.1 ETH } /** * @notice Check if traits is allowed for tribe and hasn't been removed yet * @param tribe Tribe ID * @param trait Trait ID * @dev Trait types are restricted per tribe before deploy in AllowedColorsStorage * @return True if trait is available and allowed for tribe */ function isAvailableAndAllowedTrait(uint256 tribe, uint256 trait) public view returns (bool) { if (trait == EMPTY_TRAIT) return true; if (trait >= 150) return isAvailableTrait(trait); AllowedColorsStorage colorsStorage = AllowedColorsStorage(_storageAddress); return colorsStorage.isAllowedColor(tribe, trait); } // Internal functions /** * @notice Base URI for computing {tokenURI}. Overrides ERC721 default * @return Base token URI linked to IPFS metadata */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenUri; } // Private functions /** * @notice Validate character traits * @param char Indexed list of character traits * @param head Indexed list of head traits * @param cloth Indexed list of clothing options * @param acc Indexed list of accessories * @param items Indexed list of items */ function _validateTraits( uint256[5] memory char, uint256[3] memory head, uint256[6] memory cloth, uint256[6] memory acc, uint256[2] memory items ) private view { uint256 tribe = char[0]; require(tribe > 0 && (tribe <= 6 || (tribe <= 9 && _msgSender() == owner())), "Tribe incorrect"); require(_isTraitInRange(char[1], 10, 69) || _isTraitInRange(char[1], 119, 149), "Skin color incorrect"); require(_isTraitInRange(char[2], 70, 100) || _isTraitInRange(char[2], 119, 149), "Fur color incorrect"); require(_isTraitInRange(char[3], 101, 109) || _isTraitInRange(char[3], 119, 149), "Eye color incorrect"); require(_isTraitInRange(char[4], 110, 118) || _isTraitInRange(char[4], 119, 149), "Pupil color incorrect"); require(_isTraitInRange(head[0], 150, 262), "Hair incorrect"); require(_isTraitInRange(head[1], 263, 276), "Mouth incorrect"); require(_isTraitInRange(head[2], 277, 339), "Beard incorrect"); require(_isTraitInRange(cloth[0], 340, 438), "Top incorrect"); require(_isTraitInRange(cloth[1], 439, 514), "Outerwear incorrect"); require(_isTraitInRange(cloth[2], 515, 555), "Print incorrect"); require(_isTraitInRange(cloth[3], 556, 657), "Bottom incorrect"); require(_isTraitInRange(cloth[4], 658, 694), "Footwear incorrect"); require(_isTraitInRange(cloth[5], 695, 706), "Belt incorrect"); require(_isTraitInRange(acc[0], 707, 749), "Hat incorrect"); require(_isTraitInRange(acc[1], 750, 799), "Eyewear incorrect"); require(_isTraitInRange(acc[2], 800, 809), "Piercing incorrect"); require(_isTraitInRange(acc[3], 810, 821), "Wrist accessory incorrect"); require(_isTraitInRange(acc[4], 822, 846), "Hands accessory incorrect"); require(_isTraitInRange(acc[5], 847, 883), "Neckwear incorrect"); require(_isTraitInRange(items[0], 884, 975), "Left item incorrect"); require(_isTraitInRange(items[1], 976, 1023), "Right item incorrect"); require(isAvailableAndAllowedTrait(tribe, char[1]), "Skin color unavailable"); require(isAvailableAndAllowedTrait(tribe, char[2]), "Fur color unavailable"); require(isAvailableAndAllowedTrait(tribe, char[3]), "Eye color unavailable"); require(isAvailableAndAllowedTrait(tribe, char[4]), "Pupil color unavailable"); require(isAvailableAndAllowedTrait(tribe, head[0]), "Hair unavailable"); require(isAvailableAndAllowedTrait(tribe, head[1]), "Mouth unavailable"); require(isAvailableAndAllowedTrait(tribe, head[2]), "Beard unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[0]), "Top unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[1]), "Outerwear unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[2]), "Print unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[3]), "Bottom unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[4]), "Footwear unavailable"); require(isAvailableAndAllowedTrait(tribe, cloth[5]), "Belt unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[0]), "Hat unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[1]), "Eyewear unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[2]), "Piercing unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[3]), "Wrist accessory unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[4]), "Hand accessory unavailable"); require(isAvailableAndAllowedTrait(tribe, acc[5]), "Neckwear unavailable"); require(isAvailableAndAllowedTrait(tribe, items[0]), "Left item unavailable"); require(isAvailableAndAllowedTrait(tribe, items[1]), "Right item unavailable"); } /** * @notice Mints NFT if unique and attempts to remove a random trait * @param traitCombo Trait combo provided from _generateTraitCombo */ function _storeNewCharacter(uint256 traitCombo) private { require(isUnique(traitCombo), "NFT trait combo already exists"); _existMap[traitCombo] = true; totalSupply.increment(); uint256 newCharId = totalSupply.current(); Character memory newChar; newChar.traits = traitCombo; _characters[newCharId] = newChar; _removeRandomTrait(newCharId, traitCombo); _safeMint(_msgSender(), newCharId); } /** * @notice Attempts to remove a random trait from availability * @param newCharId ID of newly generated NFT * @param traitCombo Trait combo provided from _generateTraitCombo * @dev Any trait id besides 0, tribe ids, or body/eye colors can be removed */ function _removeRandomTrait(uint256 newCharId, uint256 traitCombo) private { uint256 numRemoved = removedTraits.length; if ( (numRemoved < 100 && newCharId % 7 == 0) || (numRemoved >= 100 && numRemoved < 200 && newCharId % 9 == 0) || (numRemoved >= 200 && numRemoved < 300 && newCharId % 11 == 0) || (numRemoved >= 300 && numRemoved < 400 && newCharId % 13 == 0) ) { uint256 randomIndex = _rngIndex(newCharId); uint16 randomTrait = _unpackUint10(traitCombo >> (randomIndex * 10)); if (randomTrait != 0) { uint256 poolSize = _originalPoolSizes[randomIndex]; bool skip = _rngSkip(poolSize); if (!skip) { removedTraits.push(randomTrait); _removedTraitsMap[randomTrait] = true; } } } } /** * @notice Simulate randomness for token index to attempt to remove excluding tribes and colors * @param tokenId ID of newly generated NFT * @dev Randomness can be anticipated and exploited but is not crucial to NFT sale * @return Number from 5-21 */ function _rngIndex(uint256 tokenId) private view returns (uint256) { uint256 randomHash = uint256(keccak256(abi.encodePacked(tokenId, block.timestamp, block.difficulty))); return (randomHash % 17) + 5; } /** * @notice Simulate randomness to decide to skip removing trait based on pool size * @param poolSize Number of trait options for a specific trait type * @dev Randomness can be anticipated and exploited but is not crucial to NFT sale * @return True if should skip this trait removal */ function _rngSkip(uint256 poolSize) private view returns (bool) { uint256 randomHash = uint256(keccak256(abi.encodePacked(poolSize, block.timestamp, block.difficulty))); int256 odds = 70 - int256(randomHash % 61); return odds < int256(500 / poolSize); } /** * @notice Checks whether trait id is in range of lower/upper bounds * @param lower lower range-bound * @param upper upper range-bound * @return True if in range */ function _isTraitInRange( uint256 trait, uint256 lower, uint256 upper ) private pure returns (bool) { return trait == EMPTY_TRAIT || (trait >= lower && trait <= upper); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./NiftyLeagueCharacter.sol"; interface INFTL is IERC20 { function burnFrom(address account, uint256 amount) external; } /** * @title NameableCharacter (Extendable to allow name changes on NFTs) * @dev Extends NiftyLeagueCharacter (ERC721) */ abstract contract NameableCharacter is NiftyLeagueCharacter { /// @notice Cost to change character name in NFTL uint256 public constant NAME_CHANGE_PRICE = 1000e18; // 1000 NFTL /// @dev Mapping if name string is already used mapping(string => bool) private _nameReserved; event NameUpdated(uint256 indexed tokenId, string previousName, string newName); // External functions /** * @notice Retrieve name of token * @param tokenId ID of NFT * @return NFT name */ function getName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "nonexistent token"); return _characters[tokenId].name; } /** * @notice Change name of NFT payable with {NAME_CHANGE_PRICE} NFTL * @param tokenId ID of NFT * @param newName New name to validate and set on NFT * @return New NFT name */ function changeName(uint256 tokenId, string memory newName) external returns (string memory) { require(_exists(tokenId), "nonexistent token"); require(_isApprovedOrOwner(_msgSender(), tokenId), "Caller is not owner nor approved"); string memory prevName = _characters[tokenId].name; require(sha256(bytes(newName)) != sha256(bytes(prevName)), "New name and old name are equal"); require(validateName(newName), "Name is not allowed"); require(!isNameReserved(newName), "Name already reserved"); INFTL(_nftlAddress).burnFrom(_msgSender(), NAME_CHANGE_PRICE); if (bytes(_characters[tokenId].name).length > 0) { _toggleReserveName(_characters[tokenId].name, false); } _toggleReserveName(newName, true); _characters[tokenId].name = newName; emit NameUpdated(tokenId, prevName, newName); return newName; } // Public functions /** * @notice Check if name is already reserved * @param nameString Name to validate * @return True if name is unique */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[_toLower(nameString)]; } /** * @notice Check for valid name string (Alphanumeric and spaces without leading or trailing space) * @param newName Name to validate * @return True if name input is valid */ function validateName(string memory newName) public pure returns (bool) { bytes memory byteName = bytes(newName); if (byteName.length < 1 || byteName.length > 32) return false; // name cannot be longer than 32 characters if (byteName[0] == 0x20 || byteName[byteName.length - 1] == 0x20) return false; // reject leading and trailing space bytes1 lastChar = byteName[0]; for (uint256 i; i < byteName.length; i++) { bytes1 currentChar = byteName[i]; if (currentChar == 0x20 && lastChar == 0x20) return false; // reject double spaces if ( !(currentChar >= 0x30 && currentChar <= 0x39) && //0-9 !(currentChar >= 0x41 && currentChar <= 0x5A) && //A-Z !(currentChar >= 0x61 && currentChar <= 0x7A) && //a-z !(currentChar == 0x20) //space ) return false; lastChar = currentChar; } return true; } // Private functions /** * @notice Reserves the name if isReserve is set to true, de-reserves if set to false * @param str NFT name string * @param isReserved Bool if name should be reserved or not */ function _toggleReserveName(string memory str, bool isReserved) private { _nameReserved[_toLower(str)] = isReserved; } /** * @notice Converts strings to lowercase * @param str Any string * @return String to lower case */ function _toLower(string memory str) private pure returns (string memory) { bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint256 i = 0; i < bStr.length; i++) { if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title AllowedColorsStorage * @dev Color indexes need to be restricted per tribe prior to NFT deploy */ contract AllowedColorsStorage is Ownable { /// @dev Mapping if color is allowed for selected tribe mapping(uint256 => mapping(uint256 => bool)) private _tribeColorAllowed; constructor() {} /** * @notice Set allowed on a given a list of colors * @param tribe Tribe ID 1-10 * @param colors List of colors to set for tribe * @param allowed Bool if the color list should be made allowed or not */ function setAllowedColorsOnTribe( uint256 tribe, uint256[] memory colors, bool allowed ) external onlyOwner { require(tribe > 0 && tribe < 10, "Invalid tribe provided"); for (uint256 i = 0; i < colors.length; i++) { _toggleColorAllowed(tribe, colors[i], allowed); } } /** * @notice Toggle color allowed on and off for a tribe * @param tribe Tribe ID * @param color Trait ID * @param allowed Bool if the color should be made allowed or not * @dev Defaults to false if never set */ function _toggleColorAllowed( uint256 tribe, uint256 color, bool allowed ) private { _tribeColorAllowed[tribe][color] = allowed; } /** * @notice Check if color is allowed for a tribe * @param tribe Tribe ID * @param color Trait ID * @return True if color is allowed for tribe */ function isAllowedColor(uint256 tribe, uint256 color) public view returns (bool) { return _tribeColorAllowed[tribe][color]; } } // 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: 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 "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** * @title NiftyLeagueCharacter (Base NFT for Nifty League characters) * @dev Extends standard ERC721 contract from OpenZeppelin */ contract NiftyLeagueCharacter is ERC721, Ownable, Pausable { using Strings for string; struct Character { uint256 traits; string name; } struct CharacterTraits { // character uint16 tribe; uint16 skinColor; uint16 furColor; uint16 eyeColor; uint16 pupilColor; // head uint16 hair; uint16 mouth; uint16 beard; // clothing uint16 top; uint16 outerwear; uint16 print; uint16 bottom; uint16 footwear; uint16 belt; // accessories uint16 hat; uint16 eyewear; uint16 piercing; uint16 wrist; uint16 hands; uint16 neckwear; // items uint16 leftItem; uint16 rightItem; } /// @dev Mapping of created character structs from token ID mapping(uint256 => Character) internal _characters; /// @dev Expected uint if no specific trait is selected uint256 internal constant EMPTY_TRAIT = 0; /// @dev Mapping if character trait combination exist mapping(uint256 => bool) internal _existMap; /// @dev Mapping if character trait has been removed mapping(uint256 => bool) internal _removedTraitsMap; /// @dev Array initialized in order to return removed trait list uint16[] internal removedTraits; /// @dev Nifty League NFTL token address address internal immutable _nftlAddress; /** * @notice Construct the Nifty League NFTs * @param nftlAddress Address of verified Nifty League NFTL contract */ constructor( address nftlAddress, string memory name, string memory symbol ) ERC721(name, symbol) { _nftlAddress = nftlAddress; } // External functions /** * @notice Triggers stopped state * @dev Requirements: The contract must not be paused */ function pauseMinting() external onlyOwner { _pause(); } /** * @notice Returns to normal state * @dev Requirements: The contract must be paused */ function unpauseMinting() external onlyOwner { _unpause(); } /** * @notice Withdraw ether from this contract (Callable by owner) */ function withdraw() external onlyOwner { uint256 balance = address(this).balance; payable(_msgSender()).transfer(balance); } /** * @notice Retrieve a list of removed character traits * @return removedTraits - list of unavailable character traits */ function getRemovedTraits() external view returns (uint16[] memory) { return removedTraits; } /** * @notice Retrieve a list of character traits for a token * @param tokenId ID of NFT * @dev Permissioning not added because it is only callable once. * @return _characterTraits - indexed list of character traits */ function getCharacterTraits(uint256 tokenId) external view returns (CharacterTraits memory _characterTraits) { require(_exists(tokenId), "nonexistent token"); Character memory character = _characters[tokenId]; _characterTraits.tribe = _unpackUint10(character.traits); _characterTraits.skinColor = _unpackUint10(character.traits >> 10); _characterTraits.furColor = _unpackUint10(character.traits >> 20); _characterTraits.eyeColor = _unpackUint10(character.traits >> 30); _characterTraits.pupilColor = _unpackUint10(character.traits >> 40); _characterTraits.hair = _unpackUint10(character.traits >> 50); _characterTraits.mouth = _unpackUint10(character.traits >> 60); _characterTraits.beard = _unpackUint10(character.traits >> 70); _characterTraits.top = _unpackUint10(character.traits >> 80); _characterTraits.outerwear = _unpackUint10(character.traits >> 90); _characterTraits.print = _unpackUint10(character.traits >> 100); _characterTraits.bottom = _unpackUint10(character.traits >> 110); _characterTraits.footwear = _unpackUint10(character.traits >> 120); _characterTraits.belt = _unpackUint10(character.traits >> 130); _characterTraits.hat = _unpackUint10(character.traits >> 140); _characterTraits.eyewear = _unpackUint10(character.traits >> 150); _characterTraits.piercing = _unpackUint10(character.traits >> 160); _characterTraits.wrist = _unpackUint10(character.traits >> 170); _characterTraits.hands = _unpackUint10(character.traits >> 180); _characterTraits.neckwear = _unpackUint10(character.traits >> 190); _characterTraits.leftItem = _unpackUint10(character.traits >> 200); _characterTraits.rightItem = _unpackUint10(character.traits >> 210); } // Public functions /** * @notice Check whether trait combo is unique * @param traitCombo Generated trait combo packed into uint256 * @return True if combo is unique and available */ function isUnique(uint256 traitCombo) public view returns (bool) { return !_existMap[traitCombo]; } /** * @notice Check whether trait is still available * @param trait ID of trait * @return True if trait has not been removed */ function isAvailableTrait(uint256 trait) public view returns (bool) { return !_removedTraitsMap[trait]; } // Internal functions /** * @notice Unpack trait id from trait list * @param traits Section within trait combo * @return Trait ID */ function _unpackUint10(uint256 traits) internal pure returns (uint16) { return uint16(traits) & 0x03FF; } /** * @notice Generates uint256 bitwise trait combo * @param character Indexed list of character traits * @param head Indexed list of head traits * @param clothing Indexed list of clothing options * @param accessories Indexed list of accessories * @param items Indexed list of items * @dev Each trait is stored in 10 bits * @return Trait combo packed into uint256 */ function _generateTraitCombo( uint256[5] memory character, uint256[3] memory head, uint256[6] memory clothing, uint256[6] memory accessories, uint256[2] memory items ) internal pure returns (uint256) { uint256 traits = character[0]; traits |= character[1] << 10; traits |= character[2] << 20; traits |= character[3] << 30; traits |= character[4] << 40; traits |= head[0] << 50; traits |= head[1] << 60; traits |= head[2] << 70; traits |= clothing[0] << 80; traits |= clothing[1] << 90; traits |= clothing[2] << 100; traits |= clothing[3] << 110; traits |= clothing[4] << 120; traits |= clothing[5] << 130; traits |= accessories[0] << 140; traits |= accessories[1] << 150; traits |= accessories[2] << 160; traits |= accessories[3] << 170; traits |= accessories[4] << 180; traits |= accessories[5] << 190; traits |= items[0] << 200; traits |= items[1] << 210; return traits; } } // 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; 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; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); }
Fallback to set NFT price to static ether value if necessary newPrice New price to set for remaining character sale Minimum value of 0.08 ETH for this to be considered in getNFTPrice/
function overrideMintPrice(uint256 newPrice) external onlyOwner { _manualMintPrice = newPrice; }
11,659,109
pragma solidity ^0.4.19; contract Ownable { /** * @dev set `owner` of the contract to the sender */ address public owner = msg.sender; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] += _value; allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event Burn(address indexed burner, uint value); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply += _amount; balances[_to] += _amount; Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to burn tokens * @param _addr The address that will have _amount of tokens burned. * @param _amount The amount of tokens to burn. */ function burn(address _addr, uint _amount) onlyOwner public { require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount); balances[_addr] -= _amount; totalSupply -= _amount; Burn(_addr, _amount); Transfer(_addr, address(0), _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract WealthBuilderToken is MintableToken { string public name = "Wealth Builder Token"; string public symbol = "WBT"; uint32 public decimals = 18; /** * how many {tokens*10^(-18)} get per 1wei */ uint public rate = 10**7; /** * multiplicator for rate */ uint public mrate = 10**7; function setRate(uint _rate) onlyOwner public { rate = _rate; } } contract Data is Ownable { // node => its parent mapping (address => address) private parent; // node => its status mapping (address => uint8) public statuses; // node => sum of all his child deposits in USD cents mapping (address => uint) public referralDeposits; // client => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private balances; // investor => balance in wei*10^(-6) available for withdrawal mapping(address => uint256) private investorBalances; function parentOf(address _addr) public constant returns (address) { return parent[_addr]; } function balanceOf(address _addr) public constant returns (uint256) { return balances[_addr] / 1000000; } function investorBalanceOf(address _addr) public constant returns (uint256) { return investorBalances[_addr] / 1000000; } /** * @dev The Data constructor to set up the first depositer */ function Data() public { // DirectorOfRegion - 7 statuses[msg.sender] = 7; } function addBalance(address _addr, uint256 amount) onlyOwner public { balances[_addr] += amount; } function subtrBalance(address _addr, uint256 amount) onlyOwner public { require(balances[_addr] >= amount); balances[_addr] -= amount; } function addInvestorBalance(address _addr, uint256 amount) onlyOwner public { investorBalances[_addr] += amount; } function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public { require(investorBalances[_addr] >= amount); investorBalances[_addr] -= amount; } function addReferralDeposit(address _addr, uint256 amount) onlyOwner public { referralDeposits[_addr] += amount; } function setStatus(address _addr, uint8 _status) onlyOwner public { statuses[_addr] = _status; } function setParent(address _addr, address _parent) onlyOwner public { parent[_addr] = _parent; } } contract Declaration { // threshold in USD => status mapping (uint => uint8) statusThreshold; // status => (depositsNumber => percentage) mapping (uint8 => mapping (uint8 => uint)) feeDistribution; // status thresholds in USD uint[8] thresholds = [ 0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000 ]; uint[5] referralFees = [50, 30, 20, 10, 5]; uint[5] serviceFees = [25, 20, 15, 10, 5]; /** * @dev The Declaration constructor to define some constants */ function Declaration() public { setFeeDistributionsAndStatusThresholds(); } /** * @dev Set up fee distribution & status thresholds */ function setFeeDistributionsAndStatusThresholds() private { // Agent - 0 setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]); // SilverAgent - 1 setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]); // Manager - 2 setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]); // ManagerOfGroup - 3 setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]); // ManagerOfRegion - 4 setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]); // Director - 5 setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]); // DirectorOfGroup - 6 setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]); // DirectorOfRegion - 7 setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]); } /** * @dev Set up specific fee and status threshold * @param _st The status to set up for * @param _percentages Array of pecentages, which should go to member * @param _threshold The minimum amount of sum of children deposits to get * the status _st */ function setFeeDistributionAndStatusThreshold( uint8 _st, uint8[5] _percentages, uint _threshold ) private { statusThreshold[_threshold] = _st; for (uint8 i = 0; i < _percentages.length; i++) { feeDistribution[_st][i] = _percentages[i]; } } } contract Investors is Ownable { // investors /* "0x418155b19d7350f5a843b826474aa2f7623e99a6","0xbeb7a29a008d69069fd10154966870ff1dda44a0","0xa9cb1b8ba1c8facb92172e459389f80d304595a3","0xf3f2bf9be0ccc8f27a15ccf18d820c0722e8996a","0xa0f36ac9f68c1a4594ef5cec29dc9b1cc67f822c","0xc319278cca404e3a479b088922e4117feb4cec9d","0xe633c933529d6fd7c6147d2b0dc51bfbe3304e56","0x5bd2c1f2f06b16e427a4ec3a6beef6263fd506da","0x52c4f101d0367c3f9933d0c14ea389e74ad00352","0xf7a0d2149f324a0b607ebf23df671acc4e9da6d2","0x0418df662bb2994262bb720d477e558a59e19490","0xf0de6520e0726ba3d84611f84867aa9987391402","0x1e895274a9570f150f11ae0ed86dd42a53208b81","0x95a247bef71f6b234e9805d1493366a302a498e4","0x9daaeaf355f69f7176a0145df6d1769d7f14553b","0x029136181d87c6f0979431255424b5fad78e8491","0x7e1f5669d9e1c593a495c5cec384ca32ad4a09fc","0x46c7e04fdaaa1a9298e63ca2fd47b0004cb236bf","0x5933fa485863da06584057494f0f6660d3c1477c","0x4290231804dd59947aff9fcef925287e44906e7b","0x2feaf2101b3f9943a81567badb56e3780946ce3f","0x5b602c34ba643913908f69a4cd5846a07ed3915b","0x146308896955030ce3bcc6030bab142afddaa1e6","0x9fc61b75451fabf5b5b78e03bacaf8bb592541fc","0x87f7636f7856466b6c6bce999574a784387e2b78","0x024db1f560327ab5174f1a737caf446b5644c709","0x715c248e621cbdb6f091bf653bb4bc331d2f9b1e","0xfe92a23b497140ba055a91ade89d91f95f8e5153","0xc3426e0e0634725a628a7a21bfd49274e1f24733","0xb12a79b9dba8bbb9ed5e329466a9c2703da38dbd","0x44d8336749ebf584a4bcd636cefe83e6e0b33e7d","0x89c91460c3bdc164250e5a27351c743c070c226a","0xe0798a1b847f450b5d4819043d27a380a4715af8","0xeac5e75252d902cb7f8473e45fff9ceb391c536b","0xea53e88876a6da2579d837a559b31b08d6750681","0x5df22fac00c45ef7b5c285c54a006798f42bbc6e","0x09899f20064b5e67d02f6a97ef412564977ee193","0xc572f18d0a4a65f6e612e6de484dbc15b8839df3","0x397b9719e720c0d33fe7dcc004958e56636cbf82","0x577de83b60299df60cc7fce7ac78d3a5d880aa95","0x9a716298949b16c4610b40ba1d19e96d3286c35c","0x60ef523f3845e38a20b63344a4e9ec689773ead6","0xe34252e3efe0514c5fb76c9fb39ff31f554d6659","0xbabfbdf4f422d36c00e448cc562ce0f5dbe47d64","0x2608cca4aff4cc3008ac6bd22e0664348ecee088","0x0dd1d3102f89d4ee7c260048cbe01933f17debde","0xdbb28fafc4ecd7736247aca7dc8e20782ca86a7a","0x6201fc413bb9292527956a70e7575436d5135ce1","0xa836f4cfb8fd3e5bccc9c7a6a678f2a5928b7c79","0x85dce799fd059d86c420eb4e3c1bd89e323b7b12","0xdef2086c6bbdc8b0f6e130907f05345b44af8cc3","0xc1004695ce07ef5efb1d218672e5cfcb659c5900","0x227a5b4bb4cffc2b907d9f586dd100989efeee56","0xd372b3d43ba8ea406f64dbc68f70ec812e54fbc8","0xdf6c417cdb27bc0c877a0e121a2c58ad884e85c6","0x090f4d53b5d7ebcb8e348709cdb708d80cd199f0","0x2499b302b6f5e57f54c1c7a326813e3dffddcd1a","0x3114024a034443e972707522d911fc709f62dd3e","0x30b864f49cef510b1173a5bfc31e77b0b59daf9e","0x9a9680f5ddee6cef96ef36ab506f4b6d3198c35e","0x08018337b9b138b631cd325168c3d5014df6e18b","0x2ac345a4ec1615c3a236099ebbed4911673bbfa5","0x2b9fd54828cd443b7c411419b058b44bd02fdc49","0x208713a63460d44e5a83ae8e8f7333496a05065e","0xe4052eb7ba8891ee7ccd7551faaa5f4c421904e7","0x74bc9db1ac813db06f771bcff359e9237b01c906","0x033dd047a042ea873ca27af36b64ca566a006e97","0xb4721808a3f2830a1708967302443b53f5943429","0xc91fbb815c2f4944d8c6846be6ac0e30f5a037df","0x19ef947c276436ac11a8be15567909a37d824e73","0x079eefd69c5a4c5e4c9ee3fa08c2a2964da3e11a","0x11fb64be296590f948d56daab6c2d102c9842b08","0x06ec97feaeb0f4b9a75f9671d6b62bfadaf18ddd","0xaeda3cff45032695fb2cf4f584cda822bd5d8b7e","0x9f377085d3da85107cd68bd08bdd9a1b862d44e0","0xb46b8d1c313c52fd422fe189dde1b4d0800a5e0f","0x99039fa34510c7321f4d19ea337c80cc14cc885d","0x378aba0f47c7790ed0e5ca61749b0025d1208a5d","0x4395e1db93d4e2f4583a4f87494eb0aea057b8fd","0xa4035578750564e48abfb5ba1d6eec1da1bf366f","0xb611b39eb6c16dae3754e514ddd5f02fcadd765f","0x67d41491ddc004e899a3faf109f526cd717fe6d8","0x58e2c10865f9a1668e800c91b6a3d7b3416fb26c","0x04e34355ced9d532c9bc01d5e569f31b6d46cd50","0xf80358cabdc9b9b79570b6f073a861cf5567bb57","0xbdacb079fc17a00d945f01f4f9bd5d03cfcd5b6c","0x387a723060bc42a7796c76197d2d3b41b4c43d19","0xa04cc8fc56c34ab8104f63c11bf211de4bb7b0aa","0x3bf8b5ede7501519d41792715215735d8f40af10","0x6c3a13bac5cf61b1927562a927e89ca6b5d034d6","0x9899aecef15de43eec04859be649ac4c50330886","0xa4d25bac971ca08b47a908a070b6362102206c12" "0xf88d963dc3f58fe6e71879543e57734e8152f70d","0x7b30a000f7ae56ee6206cbd9fb20c934b4bbb5d1","0xb2f0e5330e90559a738eda0df156635e18a145fd","0x5b2c07b6cce506f2293f1b32dc33d9928b8c9ada","0x5a967c0e38cb3bfad90df288ce238699cc47b5e3","0x0e686d6f3c897cae3984b80b5f6a7c785c708718","0xa8ea0b6bc70502644c0644fb4c0810540a1fa261","0xc70e278819ef5aec6b3ededc21e2981557e14443","0x477b5ae32ffcd34eb25f0c52866d4f602982dc6f","0x3e72a45fbc6a0858b506a0c7bedff79af75ae37c","0x1430e272a50703ef46d8ed5aa01e1ced71245341","0xc87d0bb90a6105a66fd5105c6746218d381b8207","0x0ed7f98b6177d0c15e27704f2bae4d068b8594d5","0x09a627b57879eb625cd8b7c59ffa363222553c23","0x0fdbc41046590ef7ee2a73b9808fd5bd7e189ac4","0x6a4b68af67a3b4a98fe1a59210dd3d775e567729","0x442a3daf774329fee3e904e86ddec1191f4be3ce","0x9efa8fe7fa51c8b36ab902046f879b035520f556","0x510e8e58b8ce4acaa6866e59dfc0fa339ea358e5","0x374831251283aa63aee6506ac6580479aaf3c22b","0xf758c498d020c0b92f2116d09d7ef6509c2c71bd","0xd83e8281ffcfb0ff96236e99ba66aabb8dcc7920","0x3670c3a5e65b757db8c82b12dd92057ac19d41fa","0xfd28eb7e3e5e3406ce6b82045d487c2be294cd38","0x2d23cd492096b903e4595ccdac74e49692a6ea8e","0x94d3a0a19ed5448052c549fd1f69f54c5f1fd8c5","0x8e5354ac59cee09d252e379a3534053306022ebe","0xa66f3700dda0147c56c2970202768c956c644ffd","0xf11d32baef6221f36916c58844cd8e9813c0af47","0x384a9bc1de23b36c2a23b963e57c8cd85b0d592c","0xbd00dfbaaa1abaa7948c7b2a6bed6e644293cc1c","0xa99a28afcbd4ab09a2ef2c0932becd0368225ee6","0xe554084d77bc6e510eed7276cb6033865375b669","0xe7582fa53531915a2fef5a81b98969d0091d8d44","0x5f15db1d209fa6fd3c667fb086d3d89e3793511f","0x7e9ff5348d57d3427e24b7e104ad5acf039edaf2","0xb4fb1a01483454d75a0cdfa983b99236c4c91111","0x4a7cc5eebfe019efab06c1fa9ae8453dc63ba84e","0xb6fc08d5043b51ac05cdbd88afaab0e4422762d0","0xb18365f4f1e95287a5f85c8a67cebee9e6164c31","0xaf575cfb94d65eaeaace749868282d0e26e4608a","0x3d07e5ff3a2d29ee17584dff60cc99bb4cd79c3d","0x08f0afc93fbc8188150f4bcab004e259cd4785aa","0x65ac3ed81f101e5651c72c4cc2d74650378b5b0c","0x58aef4fc6b54cb53683a6481655021109b8d4dce","0x6aa43e24604577574a0632524a1f4c21d70a61e2","0xbee55aa5ad9953294ecac83a6b62f10c8155444b","0x99dc885ac6ec9873e2409d5a31e7f525c1897e09","0x53a0622034680d64bd0f139df5e989d70b194a4d","0xa6ba4966f1fdd0e8560516e53490b25cf0c4fbd1","0xbd1b95ee4621ecda41961da61277e17e52f37dbf","0xf6481b881eea526ae36cbe11d58d641f96f04a77","0xd158d53d75eac0dda9d2dedf3418d071a2fd44ee","0xb22697e3f33544da7782c8197d07704e1906a3bf","0xa3237e67df409dca45930c1f5f671251adc202be","0x72b26f2dded753a01f391322b00f9a85a77c7fda","0x203fbf3a77bdf35f7aca220b363272896db91d57","0xb1be2f4d72eb87dfcf7ed93c8ec16e4040e52560","0xc60d8a0313ede22194ebe6285471f72f9bcdcda0","0x9888e7423ea48413a4c90a10c76ca5f90d065e1f","0x0be856768ad0ec5b45464ce5202e2c337224cebf","0x3b54ea00a74b116510c4f73a3fc19a62991aaf64","0xe72aa06ffe7058f73622f219af164369c03e3a41","0x7e71fada017d9af455f38db4957d527f51fe1bc5","0x78430e58934220f37ca6b9dbe622f076ad0eb3f5","0x0c765e201bb43d49ab5b44d40d3cf1d219424821","0x4739d251b40028761bbd8034a21919d926f23b45","0x00a7c7bc71022032f6ef3f699b212c9450875740","0x0d4f50b0d43d34a163b8dd7c33fbcc92a19cfa59","0x9284fbc0cc35d9b835de2b00b6b7093075527f6b","0x3564e101b32fe5f3c99e8da823ac003373c26d33","0xf5a358f228dc964fa7c703cb6ad9f6002ce77b17","0x8297a09b5dac9e60896c787f0995ac06441ab14f","0xed8c9b4fd60a6e4ae66c38f5819cffb360af5dd5","0x23009de4ec4a666ba719656d844e42e264e14c6b","0x63227f4492c6bbd9e1015f2c864a31eef1465cd3","0xf3e0ec409386ea202b15d97bb8dd2d131917e3b1","0x981154fafb3a5aeee43d984ee255e5121ce79790","0x49a4598cdf112b5848c11c465d39989fcb5cb6c1","0x575ca03f00f9e5566d85dc095165998953ab0753","0x09d87f2979c4ac6c9d4077d1f5d94cb9aadf43ca","0x0b4575867757b3982379f4d05c92fd2d019247a0","0x8c666d40e2ac961885d675e58e3115b859dac6c1","0x34a3401ebe8431d44efee9948c4b641142407aa8","0x1683512dbcce189ea6042862a2ba4abd4886623b","0x72d45f733336f6f03ef20c1ad4f51ff6b7f90186","0x569fe010fe2d40037c029537eef78aa9b0e018f9","0x061def9fab3aee4161711d4c040d138a273893b5","0xe77e2ae67e1152425c75ff56291d03d92f5d3cad","0x93ebdeb0b0c967f5cc1a10f481569e1871b7d7cd","0x6d7910f900fc3e3f2e2b6d5d8aad43bc6a232685","0xb16e28be300f579a81f2b80fdd5a95cf168bf3a4" "0xd69835daeee01601ea991efe9fd0309c64c07d42","0x30b45ed69250a160ee91dadab2986d21626d7f4b","0xd28075489da5f9ef51bcc61668c114296a8e8603","0xb63c5cb479034bacc04266536e32aeeb9f958059","0x5f81fe78b5c238afd97a32c572aa04d87b730147","0xb98c8d7d64ef60cc76410f31c19570da0c4d9f12","0x031eb1c3a9909ea26d07f194abe5ad7f6945a482","0x83691573a4fdb5ff2cdbe2df155da09810a3c2bc","0x6722a482e1f3b797e69f98a3324b6660b9c6baa5","0xbda61db5824240280ed000a57ed5e6f70d552dd6","0x58605742105060e5c3070b88b0f51eca7f022d06","0xb4754815ccfc9c98a80f71a0a2c97471188bd556","0x50503144f253e6f05103b643c082ebf215436d95","0xd0dbef9f712ee0ca05fe48b6a40f5b774a109feb" */ address[] public investors; // investor address => percentage * 10^(-2) /* 3026,1500,510,462,453,302,250,250,226,220,150,129,100,100,60,50,50,50,50,50,50,50,50,50,50,40,40,30,27,26,25,25,25,25,25,25,25,25,23,20,19,15,15,15,15,15,14,14,13,13,13,13,12,12,11,11,11,11,11,11,10,10,10,10,10,10,10,10,12,9,9,8,8,8,8,7,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,6 6,125,50,5,8,50,23,3,115,14,10,50,5,5 */ mapping (address => uint) public investorPercentages; /** * @dev Add investors */ function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public { for (uint i = 0; i < _investors.length; i++) { investors.push(_investors[i]); investorPercentages[_investors[i]] = _investorPercentages[i]; } } /** * @dev Get investors count * @return uint count */ function getInvestorsCount() public constant returns (uint) { return investors.length; } /** * @dev Get investors' fee depending on the current year * @return uint8 The fee percentage, which investors get */ function getInvestorsFee() public constant returns (uint8) { //01/01/2020 if (now >= 1577836800) { return 1; } //01/01/2019 if (now >= 1546300800) { return 5; } return 10; } } contract Referral is Declaration, Ownable { using SafeMath for uint; // reference to token contract WealthBuilderToken private token; // reference to data contract Data private data; // reference to investors contract Investors private investors; // investors balance to be distributed in wei*10^(2) uint public investorsBalance; /** * how many USD cents get per ETH */ uint public ethUsdRate; /** * @dev The Referral constructor to set up the first depositer, * reference to system token, data & investors and set ethUsdRate */ function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public { ethUsdRate = _ethUsdRate; // instantiate token & data contracts token = WealthBuilderToken(_token); data = Data(_data); investors = Investors(_investors); investorsBalance = 0; } /** * @dev Callback function */ function() payable public { } function invest(address client, uint8 depositsCount) payable public { uint amount = msg.value; // if less then 5 deposits if (depositsCount < 5) { uint serviceFee; uint investorsFee = 0; if (depositsCount == 0) { uint8 investorsFeePercentage = investors.getInvestorsFee(); serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage)); investorsFee = amount * investorsFeePercentage; investorsBalance += investorsFee; } else { serviceFee = amount * serviceFees[depositsCount]; } uint referralFee = amount * referralFees[depositsCount]; // distribute deposit fee among users above on the branch & update users' statuses distribute(data.parentOf(client), 0, depositsCount, amount); // update balance & number of deposits of user uint active = (amount * 100) .sub(referralFee) .sub(serviceFee) .sub(investorsFee); token.mint(client, active / 100 * token.rate() / token.mrate()); // update owner`s balance data.addBalance(owner, serviceFee * 10000); } else { token.mint(client, amount * token.rate() / token.mrate()); } } /** * @dev Recursively distribute deposit fee between parents * @param _node Parent address * @param _prevPercentage The percentage for previous parent * @param _depositsCount Count of depositer deposits * @param _amount The amount of deposit */ function distribute( address _node, uint _prevPercentage, uint8 _depositsCount, uint _amount ) private { address node = _node; uint prevPercentage = _prevPercentage; // distribute deposit fee among users above on the branch & update users' statuses while(node != address(0)) { uint8 status = data.statuses(node); // count fee percentage of current node uint nodePercentage = feeDistribution[status][_depositsCount]; uint percentage = nodePercentage.sub(prevPercentage); data.addBalance(node, _amount * percentage * 10000); //update refferals sum amount data.addReferralDeposit(node, _amount * ethUsdRate / 10**18); //update status updateStatus(node, status); node = data.parentOf(node); prevPercentage = nodePercentage; } } /** * @dev Update node status if children sum amount is enough * @param _node Node address * @param _status Node current status */ function updateStatus(address _node, uint8 _status) private { uint refDep = data.referralDeposits(_node); for (uint i = thresholds.length - 1; i > _status; i--) { uint threshold = thresholds[i] * 100; if (refDep >= threshold) { data.setStatus(_node, statusThreshold[threshold]); break; } } } /** * @dev Distribute fee between investors */ function distributeInvestorsFee(uint start, uint end) onlyOwner public { for (uint i = start; i < end; i++) { address investor = investors.investors(i); uint investorPercentage = investors.investorPercentages(investor); data.addInvestorBalance(investor, investorsBalance * investorPercentage); } if (end == investors.getInvestorsCount()) { investorsBalance = 0; } } /** * @dev Set token exchange rate * @param _rate wbt/eth rate */ function setRate(uint _rate) onlyOwner public { token.setRate(_rate); } /** * @dev Set ETH exchange rate * @param _ethUsdRate eth/usd rate */ function setEthUsdRate(uint _ethUsdRate) onlyOwner public { ethUsdRate = _ethUsdRate; } /** * @dev Add new child * @param _inviter parent * @param _invitee child */ function invite( address _inviter, address _invitee ) public onlyOwner { data.setParent(_invitee, _inviter); // Agent - 0 data.setStatus(_invitee, 0); } /** * @dev Set _status for _addr * @param _addr address * @param _status ref. status */ function setStatus(address _addr, uint8 _status) public onlyOwner { data.setStatus(_addr, _status); } /** * @dev Set investors contract address * @param _addr address */ function setInvestors(address _addr) public onlyOwner { investors = Investors(_addr); } /** * @dev Withdraw _amount for _addr * @param _addr withdrawal address * @param _amount withdrawal amount */ function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner { uint amount = investor ? data.investorBalanceOf(_addr) : data.balanceOf(_addr); require(amount >= _amount && this.balance >= _amount); if (investor) { data.subtrInvestorBalance(_addr, _amount * 1000000); } else { data.subtrBalance(_addr, _amount * 1000000); } _addr.transfer(_amount); } /** * @dev Withdraw contract balance to _addr * @param _addr withdrawal address */ function withdrawOwner(address _addr, uint256 _amount) public onlyOwner { require(this.balance >= _amount); _addr.transfer(_amount); } /** * @dev Withdraw corresponding amount of ETH to _addr and burn _value tokens * @param _addr withdrawal address * @param _amount amount of tokens to sell */ function withdrawToken(address _addr, uint256 _amount) onlyOwner public { token.burn(_addr, _amount); uint256 etherValue = _amount * token.mrate() / token.rate(); _addr.transfer(etherValue); } /** * @dev Transfer ownership of token contract to _addr * @param _addr address */ function transferTokenOwnership(address _addr) onlyOwner public { token.transferOwnership(_addr); } /** * @dev Transfer ownership of data contract to _addr * @param _addr address */ function transferDataOwnership(address _addr) onlyOwner public { data.transferOwnership(_addr); } } contract PChannel is Ownable { Referral private refProgram; // fixed deposit amount in USD cents uint private depositAmount = 100000; // max deposit amount in USD cents uint private maxDepositAmount = 125000; // investor => number of deposits mapping (address => uint8) private deposits; function PChannel(address _refProgram) public { refProgram = Referral(_refProgram); } function() payable public { uint8 depositsCount = deposits[msg.sender]; // check if user has already exceeded 15 deposits limit require(depositsCount < 15); uint amount = msg.value; uint usdAmount = amount * refProgram.ethUsdRate() / 10**18; // check if deposit amount is valid require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount); refProgram.invest.value(amount)(msg.sender, depositsCount); deposits[msg.sender]++; } /** * @dev Set investors contract address * @param _addr address */ function setRefProgram(address _addr) public onlyOwner { refProgram = Referral(_addr); } }
Transfer ownership of data contract to _addr _addr address/
function transferDataOwnership(address _addr) onlyOwner public { data.transferOwnership(_addr); }
626,894
// SPDX-License-Identifier: MIT pragma solidity 0.8.3; import "../controller/ControllerInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Bridge is Ownable { enum RequestStatus {PENDING, CANCELED, APPROVED, REJECTED} struct Request { address requester; // sender of the request. uint amount; // amount of token to mint/burn. string depositAddress; // custodian's asset address in mint, broker's asset address in burn. string txid; // asset txid for sending/redeeming asset in the mint/burn process. uint nonce; // serial number allocated for each request. uint timestamp; // time of the request creation. RequestStatus status; // status of the request. } ControllerInterface public controller; // mapping between broker to the corresponding custodian deposit address, used in the minting process. // by using a different deposit address per broker the custodian can identify which broker deposited. mapping(address=>string) public custodianDepositAddress; // mapping between broker to the its deposit address where the asset should be moved to, used in the burning process. mapping(address=>string) public brokerDepositAddress; // mapping between a mint request hash and the corresponding request nonce. mapping(bytes32=>uint) public mintRequestNonce; // mapping between a burn request hash and the corresponding request nonce. mapping(bytes32=>uint) public burnRequestNonce; Request[] public mintRequests; Request[] public burnRequests; constructor(address _controller) { require(_controller != address(0), "invalid _controller address"); controller = ControllerInterface(_controller); transferOwnership(_controller); } modifier onlyBroker() { require(controller.isBroker(msg.sender), "sender not a broker."); _; } modifier onlyCustodian() { require(controller.isCustodian(msg.sender), "sender not a custodian."); _; } event CustodianDepositAddressSet(address indexed broker, address indexed sender, string depositAddress); function setCustodianDepositAddress( address broker, string memory depositAddress ) external onlyCustodian returns (bool) { require(broker != address(0), "invalid broker address"); require(controller.isBroker(broker), "broker address is not a real broker."); require(!isEmptyString(depositAddress), "invalid asset deposit address"); custodianDepositAddress[broker] = depositAddress; emit CustodianDepositAddressSet(broker, msg.sender, depositAddress); return true; } event BrokerDepositAddressSet(address indexed broker, string depositAddress); function setBrokerDepositAddress(string memory depositAddress) external onlyBroker returns (bool) { require(!isEmptyString(depositAddress), "invalid asset deposit address"); brokerDepositAddress[msg.sender] = depositAddress; emit BrokerDepositAddressSet(msg.sender, depositAddress); return true; } event MintRequestAdd( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function addMintRequest( uint amount, string memory txid, string memory depositAddress ) external onlyBroker returns (bool) { require(!isEmptyString(depositAddress), "invalid asset deposit address"); require(compareStrings(depositAddress, custodianDepositAddress[msg.sender]), "wrong asset deposit address"); uint nonce = mintRequests.length; uint timestamp = getTimestamp(); Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); mintRequestNonce[requestHash] = nonce; mintRequests.push(request); emit MintRequestAdd(nonce, msg.sender, amount, depositAddress, txid, timestamp, requestHash); return true; } event MintRequestCancel(uint indexed nonce, address indexed requester, bytes32 requestHash); function cancelMintRequest(bytes32 requestHash) external onlyBroker returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); require(msg.sender == request.requester, "cancel sender is different than pending request initiator"); mintRequests[nonce].status = RequestStatus.CANCELED; emit MintRequestCancel(nonce, msg.sender, requestHash); return true; } event MintConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function confirmMintRequest(bytes32 requestHash) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); mintRequests[nonce].status = RequestStatus.APPROVED; require(controller.mint(request.requester, request.amount), "mint failed"); emit MintConfirmed( request.nonce, request.requester, request.amount, request.depositAddress, request.txid, request.timestamp, requestHash ); return true; } event MintRejected( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 requestHash ); function rejectMintRequest(bytes32 requestHash) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingMintRequest(requestHash); mintRequests[nonce].status = RequestStatus.REJECTED; emit MintRejected( request.nonce, request.requester, request.amount, request.depositAddress, request.txid, request.timestamp, requestHash ); return true; } event Burned( uint indexed nonce, address indexed requester, uint amount, string depositAddress, uint timestamp, bytes32 requestHash ); function burn(uint amount) external onlyBroker returns (bool) { string memory depositAddress = brokerDepositAddress[msg.sender]; require(!isEmptyString(depositAddress), "broker asset deposit address was not set"); uint nonce = burnRequests.length; uint timestamp = getTimestamp(); // set txid as empty since it is not known yet. string memory txid = ""; Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); burnRequestNonce[requestHash] = nonce; burnRequests.push(request); require(controller.getToken().transferFrom(msg.sender, address(controller), amount), "transfer tokens to burn failed"); require(controller.burn(amount), "burn failed"); emit Burned(nonce, msg.sender, amount, depositAddress, timestamp, requestHash); return true; } event BurnConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 inputRequestHash ); function confirmBurnRequest(bytes32 requestHash, string memory txid) external onlyCustodian returns (bool) { uint nonce; Request memory request; (nonce, request) = getPendingBurnRequest(requestHash); burnRequests[nonce].txid = txid; burnRequests[nonce].status = RequestStatus.APPROVED; burnRequestNonce[calcRequestHash(burnRequests[nonce])] = nonce; emit BurnConfirmed( request.nonce, request.requester, request.amount, request.depositAddress, txid, request.timestamp, requestHash ); return true; } function getMintRequest(uint nonce) external view returns ( uint requestNonce, address requester, uint amount, string memory depositAddress, string memory txid, uint timestamp, string memory status, bytes32 requestHash ) { Request memory request = mintRequests[nonce]; string memory statusString = getStatusString(request.status); requestNonce = request.nonce; requester = request.requester; amount = request.amount; depositAddress = request.depositAddress; txid = request.txid; timestamp = request.timestamp; status = statusString; requestHash = calcRequestHash(request); } function getMintRequestsLength() external view returns (uint length) { return mintRequests.length; } function getBurnRequest(uint nonce) external view returns ( uint requestNonce, address requester, uint amount, string memory depositAddress, string memory txid, uint timestamp, string memory status, bytes32 requestHash ) { Request storage request = burnRequests[nonce]; string memory statusString = getStatusString(request.status); requestNonce = request.nonce; requester = request.requester; amount = request.amount; depositAddress = request.depositAddress; txid = request.txid; timestamp = request.timestamp; status = statusString; requestHash = calcRequestHash(request); } function getBurnRequestsLength() external view returns (uint length) { return burnRequests.length; } function getTimestamp() internal view returns (uint) { // timestamp is only used for data maintaining purpose, it is not relied on for critical logic. return block.timestamp; // solhint-disable-line not-rely-on-time } function getPendingMintRequest(bytes32 requestHash) internal view returns (uint nonce, Request memory request) { require(requestHash != 0, "request hash is 0"); nonce = mintRequestNonce[requestHash]; request = mintRequests[nonce]; validatePendingRequest(request, requestHash); } function getPendingBurnRequest(bytes32 requestHash) internal view returns (uint nonce, Request memory request) { require(requestHash != 0, "request hash is 0"); nonce = burnRequestNonce[requestHash]; request = burnRequests[nonce]; validatePendingRequest(request, requestHash); } function validatePendingRequest(Request memory request, bytes32 requestHash) internal pure { require(request.status == RequestStatus.PENDING, "request is not pending"); require(requestHash == calcRequestHash(request), "given request hash does not match a pending request"); } function calcRequestHash(Request memory request) internal pure returns (bytes32) { return keccak256(abi.encode( request.requester, request.amount, request.depositAddress, request.txid, request.nonce, request.timestamp )); } function compareStrings (string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))); } function isEmptyString (string memory a) internal pure returns (bool) { return (compareStrings(a, "")); } function getStatusString(RequestStatus status) internal pure returns (string memory) { if (status == RequestStatus.PENDING) { return "pending"; } else if (status == RequestStatus.CANCELED) { return "canceled"; } else if (status == RequestStatus.APPROVED) { return "approved"; } else if (status == RequestStatus.REJECTED) { return "rejected"; } else { // this fallback can never be reached. return "unknown"; } } }
set txid as empty since it is not known yet.
function burn(uint amount) external onlyBroker returns (bool) { string memory depositAddress = brokerDepositAddress[msg.sender]; require(!isEmptyString(depositAddress), "broker asset deposit address was not set"); uint nonce = burnRequests.length; uint timestamp = getTimestamp(); string memory txid = ""; Request memory request = Request({ requester: msg.sender, amount: amount, depositAddress: depositAddress, txid: txid, nonce: nonce, timestamp: timestamp, status: RequestStatus.PENDING }); bytes32 requestHash = calcRequestHash(request); burnRequestNonce[requestHash] = nonce; burnRequests.push(request); require(controller.getToken().transferFrom(msg.sender, address(controller), amount), "transfer tokens to burn failed"); require(controller.burn(amount), "burn failed"); emit Burned(nonce, msg.sender, amount, depositAddress, timestamp, requestHash); return true; } event BurnConfirmed( uint indexed nonce, address indexed requester, uint amount, string depositAddress, string txid, uint timestamp, bytes32 inputRequestHash );
917,089
./partial_match/1/0xE2fe5E7E206e7B46CAd6A5146320e5b4b9A18E97/sources/metahashtoken.sol
Send tokens from the recipient to the recipient / check of allowed value / not enough tokens /
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){ var _allowance = allowed[_from][msg.sender]; if (_allowance < _value){ revert(); } if (balance[_from] < _value){ revert(); } balance[_to] += _value; balance[_from] -= _value; allowed[_from][msg.sender] = _allowance - _value; Transfer(_from, _to, _value); return true; }
9,226,545
// SPDX-License-Identifier: ISC pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import "./BlockLock.sol"; import "./interfaces/IxALPHA.sol"; import "./interfaces/IxTokenManager.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/IALPHAStaking.sol"; import "./interfaces/ISushiswapRouter.sol"; import "./interfaces/IUniswapV3SwapRouter.sol"; import "./interfaces/IStakingProxy.sol"; import "./helpers/StakingFactory.sol"; // solhint-disable-next-line contract-name-camelcase contract xALPHA is Initializable, ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable, IxALPHA, BlockLock { using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for SafeERC20Upgradeable; using SafeERC20 for IERC20; uint256 private constant LIQUIDATION_TIME_PERIOD = 4 weeks; uint256 private constant INITIAL_SUPPLY_MULTIPLIER = 10; uint256 private constant STAKING_PROXIES_AMOUNT = 5; uint256 private constant MAX_UINT = 2**256 - 1; address private constant ETH_ADDRESS = address(0); IWETH private weth; IERC20 private alphaToken; StakingFactory private stakingFactory; address private stakingProxyImplementation; // The total amount staked across all proxies uint256 public totalStakedBalance; uint256 public adminActiveTimestamp; uint256 public withdrawableAlphaFees; uint256 public emergencyUnbondTimestamp; uint256 public lastStakeTimestamp; IxTokenManager private xTokenManager; // xToken manager contract address private uniswapRouter; address private sushiswapRouter; SwapMode private swapMode; FeeDivisors public feeDivisors; uint24 public v3AlphaPoolFee; function initialize( string calldata _symbol, IWETH _wethToken, IERC20 _alphaToken, address _alphaStaking, StakingFactory _stakingFactory, IxTokenManager _xTokenManager, address _uniswapRouter, address _sushiswapRouter, FeeDivisors calldata _feeDivisors ) external override initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); __ERC20_init_unchained("xALPHA", _symbol); weth = _wethToken; alphaToken = _alphaToken; stakingFactory = _stakingFactory; xTokenManager = _xTokenManager; uniswapRouter = _uniswapRouter; sushiswapRouter = _sushiswapRouter; updateSwapRouter(SwapMode.UNISWAP_V3); // Approve WETH and ALPHA for both swap routers alphaToken.safeApprove(sushiswapRouter, MAX_UINT); IERC20(address(weth)).safeApprove(sushiswapRouter, MAX_UINT); alphaToken.safeApprove(uniswapRouter, MAX_UINT); IERC20(address(weth)).safeApprove(uniswapRouter, MAX_UINT); v3AlphaPoolFee = 10000; _setFeeDivisors(_feeDivisors.mintFee, _feeDivisors.burnFee, _feeDivisors.claimFee); // Initialize the staking proxies for (uint256 i = 0; i < STAKING_PROXIES_AMOUNT; ++i) { // Deploy the proxy stakingFactory.deployProxy(); // Initialize IStakingProxy(stakingFactory.stakingProxyProxies(i)).initialize(_alphaStaking); } } /* ========================================================================================= */ /* User functions */ /* ========================================================================================= */ /* * @dev Mint xALPHA using ETH * @notice Assesses mint fee * @param minReturn: Min return to pass to Uniswap trade * * This function swaps ETH to ALPHA using 1inch. */ function mint(uint256 minReturn) external payable override whenNotPaused notLocked(msg.sender) { require(msg.value > 0, "Must send ETH"); _lock(msg.sender); // Swap ETH for ALPHA uint256 alphaAmount = _swapETHforALPHAInternal(msg.value, minReturn); uint256 fee = _calculateFee(alphaAmount, feeDivisors.mintFee); _incrementWithdrawableAlphaFees(fee); return _mintInternal(alphaAmount.sub(fee)); } /* * @dev Mint xALPHA using ALPHA * @notice Assesses mint fee * * @param alphaAmount: ALPHA tokens to contribute * * The xALPHA contract must be approved to withdraw ALPHA from the * sender's wallet. */ function mintWithToken(uint256 alphaAmount) external override whenNotPaused notLocked(msg.sender) { require(alphaAmount > 0, "Must send token"); _lock(msg.sender); alphaToken.safeTransferFrom(msg.sender, address(this), alphaAmount); uint256 fee = _calculateFee(alphaAmount, feeDivisors.mintFee); _incrementWithdrawableAlphaFees(fee); return _mintInternal(alphaAmount.sub(fee)); } /* * @dev Perform mint action * @param _incrementalAlpha: ALPHA tokens to contribute * * No safety checks since internal function. After calculating * the mintAmount based on the current liquidity ratio, it mints * xALPHA (using ERC20 mint). */ function _mintInternal(uint256 _incrementalAlpha) private { uint256 mintAmount = calculateMintAmount(_incrementalAlpha, totalSupply()); return super._mint(msg.sender, mintAmount); } /* * @dev Calculate mint amount for xALPHA * * @param _incrementalAlpha: ALPHA tokens to contribute * @param totalSupply: total supply of xALPHA tokens to calculate against * * @return mintAmount: the amount of xALPHA that will be minted * * Calculate the amount of xALPHA that will be minted for a * proportionate amount of ALPHA. In practice, totalSupply will * equal the total supply of xALPHA. */ function calculateMintAmount(uint256 incrementalAlpha, uint256 totalSupply) public view override returns (uint256 mintAmount) { if (totalSupply == 0) return incrementalAlpha.mul(INITIAL_SUPPLY_MULTIPLIER); uint256 previousNav = getNav().sub(incrementalAlpha); mintAmount = incrementalAlpha.mul(totalSupply).div(previousNav); } /* * @dev Burn xALPHA tokens * @notice Will fail if pro rata balance exceeds available liquidity * @notice Assesses burn fee * * @param tokenAmount: xALPHA tokens to burn * @param redeemForEth: Redeem for ETH or ALPHA * @param minReturn: Min return to pass to 1inch trade * * Burns the sent amount of xALPHA and calculates the proportionate * amount of ALPHA. Either sends the ALPHA to the caller or exchanges * it for ETH. */ function burn( uint256 tokenAmount, bool redeemForEth, uint256 minReturn ) external override notLocked(msg.sender) { require(tokenAmount > 0, "Must send xALPHA"); _lock(msg.sender); (uint256 stakedBalance, uint256 bufferBalance) = getFundBalances(); uint256 alphaHoldings = stakedBalance.add(bufferBalance); uint256 proRataAlpha = alphaHoldings.mul(tokenAmount).div(totalSupply()); require(proRataAlpha <= bufferBalance, "Insufficient exit liquidity"); super._burn(msg.sender, tokenAmount); uint256 fee = _calculateFee(proRataAlpha, feeDivisors.burnFee); _incrementWithdrawableAlphaFees(fee); uint256 withdrawAmount = proRataAlpha.sub(fee); if (redeemForEth) { uint256 ethAmount = _swapALPHAForETHInternal(withdrawAmount, minReturn); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call{ value: ethAmount }(new bytes(0)); require(success, "ETH burn transfer failed"); } else { alphaToken.safeTransfer(msg.sender, withdrawAmount); } } /* * @inheritdoc ERC20 */ function transfer(address recipient, uint256 amount) public override notLocked(msg.sender) returns (bool) { return super.transfer(recipient, amount); } /* * @inheritdoc ERC20 */ function transferFrom( address sender, address recipient, uint256 amount ) public override notLocked(sender) returns (bool) { return super.transferFrom(sender, recipient, amount); } /* * @dev Swap ETH for ALPHA * @notice uses either Sushiswap or Uniswap V3 depending on version * * @param ethAmount: amount of ETH to swap * @param minReturn: Min return to pass to Uniswap trade * * @return amount of ALPHA returned in the swap * * These swaps always use 'exact input' - they send exactly the amount specified * in arguments to the swap, and the output amount is calculated. */ function _swapETHforALPHAInternal(uint256 ethAmount, uint256 minReturn) private returns (uint256) { uint256 deadline = MAX_UINT; if (swapMode == SwapMode.SUSHISWAP) { // SUSHISWAP IUniswapV2Router02 routerV2 = IUniswapV2Router02(sushiswapRouter); address[] memory path = new address[](2); path[0] = address(weth); path[1] = address(alphaToken); uint256[] memory amounts = routerV2.swapExactETHForTokens{ value: ethAmount }( minReturn, path, address(this), deadline ); return amounts[1]; } else { // UNISWAP V3 IUniswapV3SwapRouter routerV3 = IUniswapV3SwapRouter(uniswapRouter); weth.deposit{ value: ethAmount }(); IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({ tokenIn: address(weth), tokenOut: address(alphaToken), fee: v3AlphaPoolFee, recipient: address(this), deadline: deadline, amountIn: ethAmount, amountOutMinimum: minReturn, sqrtPriceLimitX96: 0 }); uint256 amountOut = routerV3.exactInputSingle(params); return amountOut; } } /* * @dev Swap ALPHA for ETH using Uniswap * @notice uses either Sushiswap or Uniswap V3 depending on version * * @param alphaAmount: amount of ALPHA to swap * @param minReturn: Min return to pass to Uniswap trade * * @return amount of ETH returned in the swap * * These swaps always use 'exact input' - they send exactly the amount specified * in arguments to the swap, and the output amount is calculated. The output ETH * is held in the contract. */ function _swapALPHAForETHInternal(uint256 alphaAmount, uint256 minReturn) private returns (uint256) { uint256 deadline = MAX_UINT; if (swapMode == SwapMode.SUSHISWAP) { // SUSHISWAP IUniswapV2Router02 routerV2 = IUniswapV2Router02(sushiswapRouter); address[] memory path = new address[](2); path[0] = address(alphaToken); path[1] = address(weth); uint256[] memory amounts = routerV2.swapExactTokensForETH( alphaAmount, minReturn, path, address(this), deadline ); return amounts[1]; } else { // UNISWAP V3 IUniswapV3SwapRouter routerV3 = IUniswapV3SwapRouter(uniswapRouter); IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({ tokenIn: address(alphaToken), tokenOut: address(weth), fee: v3AlphaPoolFee, recipient: address(this), deadline: deadline, amountIn: alphaAmount, amountOutMinimum: minReturn, sqrtPriceLimitX96: 0 }); uint256 amountOut = routerV3.exactInputSingle(params); // Withdraw WETH weth.withdraw(amountOut); return amountOut; } } /* ========================================================================================= */ /* Management */ /* ========================================================================================= */ /* * @dev Get NAV of the xALPHA contract * @notice Combination of staked balance held in staking contract * and unstaked buffer balance held in xALPHA contract. Also * includes stake currently being unbonded (as part of staked balance) * * @return Total NAV in ALPHA * */ function getNav() public view override returns (uint256) { return totalStakedBalance.add(getBufferBalance()); } /* * @dev Get buffer balance of the xALPHA contract * * @return Total unstaked ALPHA balance held by xALPHA, minus accrued fees */ function getBufferBalance() public view override returns (uint256) { return alphaToken.balanceOf(address(this)).sub(withdrawableAlphaFees); } /* * @dev Get staked and buffer balance of the xALPHA contract, as separate values * * @return Staked and buffer balance as a tuple */ function getFundBalances() public view override returns (uint256, uint256) { return (totalStakedBalance, getBufferBalance()); } /** * @dev Get the withdrawable amount from a staking proxy * @param proxyIndex The proxy index * @return The withdrawable amount */ function getWithdrawableAmount(uint256 proxyIndex) public view override returns (uint256) { require(proxyIndex < stakingFactory.getStakingProxyProxiesLength(), "Invalid index"); return IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).getWithdrawableAmount(); } /** * @dev Get the withdrawable fee amounts * @return feeAsset The fee asset * @return feeAmount The withdrawable amount */ function getWithdrawableFees() public view returns (address feeAsset, uint256 feeAmount) { feeAsset = address(alphaToken); feeAmount = withdrawableAlphaFees; } /* * @dev Admin function to stake tokens from the buffer. * * @param proxyIndex: The proxy index to stake with * @param amount: allocation to staked balance * @param force: stake regardless of unbonding status */ function stake( uint256 proxyIndex, uint256 amount, bool force ) public override onlyOwnerOrManager { _certifyAdmin(); _stake(proxyIndex, amount, force); updateStakedBalance(); } /* * @dev Updates the staked balance of the xALPHA contract. * @notice Includes any stake currently unbonding. * * @return Total staked balance in ALPHA staking contract */ function updateStakedBalance() public override onlyOwnerOrManager { uint256 _totalStakedBalance; for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) { _totalStakedBalance = _totalStakedBalance.add( IStakingProxy(stakingFactory.stakingProxyProxies(i)).getTotalStaked() ); } // Update staked balance totalStakedBalance = _totalStakedBalance; emit UpdateStakedBalance(totalStakedBalance); } /* * @notice Admin-callable function in case of persistent depletion of buffer reserve * or emergency shutdown * @notice Incremental ALPHA will only be allocated to buffer reserve * @notice Starting a new unbonding period cancels the last one. Need to use 'force' * explicitly cancel a current unbonding.s */ function unbond(uint256 proxyIndex, bool force) public override onlyOwnerOrManager { _certifyAdmin(); _unbond(proxyIndex, force); } /* * @notice Admin-callable function to withdraw unbonded stake back into the buffer * @notice Incremental ALPHA will only be allocated to buffer reserve * @notice There is a 72-hour deadline to claim unbonded stake after the 30-day unbonding * period ends. This call will fail in the alpha staking contract if the 72-hour deadline * is expired. */ function claimUnbonded(uint256 proxyIndex) public override onlyOwnerOrManager { _certifyAdmin(); _claim(proxyIndex); updateStakedBalance(); } /* * @notice Staking ALPHA cancels any currently open * unbonding. This will not stake unless the contract * is not unbonding, or the force param is sent * @param proxyIndex: the proxy index to stake with * @param amount: allocation to staked balance * @param force: stake regardless of unbonding status */ function _stake( uint256 proxyIndex, uint256 amount, bool force ) private { require(amount > 0, "Cannot stake zero tokens"); require( !IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding() || force, "Cannot stake during unbonding" ); // Update the most recent stake timestamp lastStakeTimestamp = block.timestamp; alphaToken.safeTransfer(address(stakingFactory.stakingProxyProxies(proxyIndex)), amount); IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).stake(amount); emit Stake(proxyIndex, block.timestamp, amount); } /* * @notice Unbonding ALPHA cancels any currently open * unbonding. This will not unbond unless the contract * is not already unbonding, or the force param is sent * @param proxyIndex: the proxy index to unbond * @param force: unbond regardless of status */ function _unbond(uint256 proxyIndex, bool force) internal { require( !IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding() || force, "Cannot unbond during unbonding" ); IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).unbond(); emit Unbond( proxyIndex, block.timestamp, IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).getUnbondingAmount() ); } /* * @notice Claims any fully unbonded ALPHA. Must be called * within 72 hours after unbonding period expires, or * funds are re-staked. * * @param proxyIndex: the proxy index to claim rewards for */ function _claim(uint256 proxyIndex) internal { require(IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).isUnbonding(), "Not unbonding"); uint256 claimedAmount = IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).withdraw(); emit Claim(proxyIndex, claimedAmount); } /* * @dev Get fee for a specific action * * @param _value: the value on which to assess the fee * @param _feeDivisor: the inverse of the percentage of the fee (i.e. 1% = 100) * * @return fee: total amount of fee to be assessed */ function _calculateFee(uint256 _value, uint256 _feeDivisor) internal pure returns (uint256 fee) { if (_feeDivisor > 0) { fee = _value.div(_feeDivisor); } } /* * @dev Increase tracked amount of fees for management * * @param _feeAmount: the amount to increase management fees by */ function _incrementWithdrawableAlphaFees(uint256 _feeAmount) private { withdrawableAlphaFees = withdrawableAlphaFees.add(_feeAmount); } /* ========================================================================================= */ /* Emergency Functions */ /* ========================================================================================= */ /* * @dev Admin function for pausing contract operations. Pausing prevents mints. * */ function pauseContract() public override onlyOwnerOrManager { _pause(); } /* * @dev Admin function for unpausing contract operations. * */ function unpauseContract() public override onlyOwnerOrManager { _unpause(); } /* * @dev Public callable function for unstaking in event of admin failure/incapacitation. * * @notice Can only be called after a period of manager inactivity. Starts a 30-day unbonding * period. emergencyClaim must be called within 72 hours after the 30 day unbounding period expires. * Cancels any previous unbonding on the first call. Cannot be called again otherwise a caller * could indefinitely delay unbonding. Unbonds all staking proxy contracts. * * Once emergencyUnbondingTimestamp has been set, it is never reset unless an admin decides to. */ function emergencyUnbond() external override { require(adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp, "Liquidation time not elapsed"); uint256 thirtyThreeDaysAgo = block.timestamp - 33 days; require(emergencyUnbondTimestamp < thirtyThreeDaysAgo, "In unbonding period"); emergencyUnbondTimestamp = block.timestamp; // Unstake everything for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) { _unbond(i, true); } } /* * @dev Public callable function for claiming unbonded stake in the event of admin failure/incapacitation. * * @notice Can only be called after a period of manager inactivity. Can only be called * after a 30-day unbonding period, and must be called within 72 hours of unbound period expiry. Makes a claim * for all staking proxies */ function emergencyClaim() external override { require(adminActiveTimestamp.add(LIQUIDATION_TIME_PERIOD) < block.timestamp, "Liquidation time not elapsed"); require(emergencyUnbondTimestamp != 0, "Emergency unbond not called"); emergencyUnbondTimestamp = 0; // Claim everything for (uint256 i = 0; i < stakingFactory.getStakingProxyProxiesLength(); i++) { _claim(i); } } /* ========================================================================================= */ /* Utils/Fallback */ /* ========================================================================================= */ /* * @notice Inverse of fee i.e., a fee divisor of 100 == 1% * @notice Three fee types * @dev Mint fee 0 or <= 2% * @dev Burn fee 0 or <= 1% * @dev Claim fee 0 <= 4% */ function setFeeDivisors( uint256 mintFeeDivisor, uint256 burnFeeDivisor, uint256 claimFeeDivisor ) public override onlyOwner { _setFeeDivisors(mintFeeDivisor, burnFeeDivisor, claimFeeDivisor); } /* * @dev Internal setter for the fee divisors, with enforced maximum fees. */ function _setFeeDivisors( uint256 _mintFeeDivisor, uint256 _burnFeeDivisor, uint256 _claimFeeDivisor ) private { require(_mintFeeDivisor == 0 || _mintFeeDivisor >= 50, "Invalid fee"); require(_burnFeeDivisor == 0 || _burnFeeDivisor >= 100, "Invalid fee"); require(_claimFeeDivisor >= 25, "Invalid fee"); feeDivisors.mintFee = _mintFeeDivisor; feeDivisors.burnFee = _burnFeeDivisor; feeDivisors.claimFee = _claimFeeDivisor; emit FeeDivisorsSet(_mintFeeDivisor, _burnFeeDivisor, _claimFeeDivisor); } /* * @dev Registers that admin is present and active * @notice If admin isn't certified within liquidation time period, * emergencyUnstake function becomes callable */ function _certifyAdmin() private { adminActiveTimestamp = block.timestamp; } /* * @dev Update the AMM to use for swaps. * @param version: the swap mode - 0 for sushiswap, 1 for Uniswap V3. * * Should be used when e.g. pricing is better on one version vs. * the other. Only valid values are 0 and 1. A new version of Uniswap * or integration with another liquidity protocol will require a full * contract upgrade. */ function updateSwapRouter(SwapMode version) public override onlyOwnerOrManager { require(version == SwapMode.SUSHISWAP || version == SwapMode.UNISWAP_V3, "Invalid swap router version"); swapMode = version; emit UpdateSwapRouter(version); } /* * @dev Update the fee tier for the ETH/ALPHA Uniswap V3 pool. * @param fee: the fee tier to use. * * Should be used when trades can be executed more efficiently at a certain * fee tier, based on the combination of fees and slippage. * * Fees are expressed in 1/100th of a basis point. * Only three fee tiers currently exist. * 500 - (0.05%) * 3000 - (0.3%) * 10000 - (1%) * Not enforcing these values because Uniswap's contracts * allow them to set arbitrary fee tiers in the future. * Take care when calling this function to make sure a pool * actually exists for a given fee, and it is the most liquid * pool for the ALPHA/ETH pair. */ function updateUniswapV3AlphaPoolFee(uint24 fee) external override onlyOwnerOrManager { v3AlphaPoolFee = fee; emit UpdateUniswapV3AlphaPoolFee(v3AlphaPoolFee); } /* * @dev Emergency function in case of errant transfer of * xALPHA token directly to contract. * * Errant xALPHA can only be sent back to management. */ function withdrawNativeToken() public override onlyOwnerOrManager { uint256 tokenBal = balanceOf(address(this)); require(tokenBal > 0, "No tokens to withdraw"); IERC20(address(this)).safeTransfer(msg.sender, tokenBal); } /* * @dev Emergency function in case of errant transfer of * ERC20 token directly to proxy contracts. * * Errant ERC20 token can only be sent back to management. */ function withdrawTokenFromProxy(uint256 proxyIndex, address token) external override onlyOwnerOrManager { IStakingProxy(stakingFactory.stakingProxyProxies(proxyIndex)).withdrawToken(token); IERC20(token).safeTransfer(msg.sender, IERC20(token).balanceOf(address(this))); } /* * @dev Withdraw function for ALPHA fees. * * All fees are denominated in ALPHA, so this should cover all * fees earned via contract interactions. Fees can only be * sent to management. */ function withdrawFees() public override { require(xTokenManager.isRevenueController(msg.sender), "Callable only by Revenue Controller"); uint256 alphaFees = withdrawableAlphaFees; withdrawableAlphaFees = 0; alphaToken.safeTransfer(msg.sender, alphaFees); emit FeeWithdraw(alphaFees); } /** * @dev Exempts an address from blocklock * @param lockAddress The address to exempt */ function exemptFromBlockLock(address lockAddress) external onlyOwnerOrManager { _exemptFromBlockLock(lockAddress); } /** * @dev Removes exemption for an address from blocklock * @param lockAddress The address to remove exemption */ function removeBlockLockExemption(address lockAddress) external onlyOwnerOrManager { _removeBlockLockExemption(lockAddress); } /* * @dev Enforce functions only called by management. */ modifier onlyOwnerOrManager() { require(msg.sender == owner() || xTokenManager.isManager(msg.sender, address(this)), "Non-admin caller"); _; } /* * @dev Fallback function for received ETH. * * The contract may receive ETH as part of swaps, so only reject * if the ETH is sent directly. */ receive() external payable { // solhint-disable-next-line avoid-tx-origin require(msg.sender != tx.origin, "Errant ETH deposit"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.6.12; /** Contract which implements locking of functions via a notLocked modifier Functions are locked per address. */ contract BlockLock { // how many blocks are the functions locked for uint256 private constant BLOCK_LOCK_COUNT = 6; // last block for which this address is timelocked mapping(address => uint256) public lastLockedBlock; mapping(address => bool) public blockLockExempt; function _lock(address lockAddress) internal { if (!blockLockExempt[lockAddress]) { lastLockedBlock[lockAddress] = block.number + BLOCK_LOCK_COUNT; } } function _exemptFromBlockLock(address lockAddress) internal { blockLockExempt[lockAddress] = true; } function _removeBlockLockExemption(address lockAddress) internal { blockLockExempt[lockAddress] = false; } modifier notLocked(address lockAddress) { require(lastLockedBlock[lockAddress] <= block.number, "Address is temporarily locked"); _; } } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IxTokenManager.sol"; import "./IALPHAStaking.sol"; import "./IWETH.sol"; import "./IOneInchLiquidityProtocol.sol"; import "./IStakingProxy.sol"; import "../helpers/StakingFactory.sol"; interface IxALPHA { enum SwapMode { SUSHISWAP, UNISWAP_V3 } struct FeeDivisors { uint256 mintFee; uint256 burnFee; uint256 claimFee; } event Stake(uint256 proxyIndex, uint256 timestamp, uint256 amount); event Unbond(uint256 proxyIndex, uint256 timestamp, uint256 amount); event Claim(uint256 proxyIndex, uint256 amount); event FeeDivisorsSet(uint256 mintFee, uint256 burnFee, uint256 claimFee); event FeeWithdraw(uint256 fee); event UpdateSwapRouter(SwapMode version); event UpdateUniswapV3AlphaPoolFee(uint24 fee); event UpdateStakedBalance(uint256 totalStaked); function initialize( string calldata _symbol, IWETH _wethToken, IERC20 _alphaToken, address _alphaStaking, StakingFactory _stakingFactory, IxTokenManager _xTokenManager, address _uniswapRouter, address _sushiswapRouter, FeeDivisors calldata _feeDivisors ) external; function mint(uint256 minReturn) external payable; function mintWithToken(uint256 alphaAmount) external; function calculateMintAmount(uint256 incrementalAlpha, uint256 totalSupply) external view returns (uint256 mintAmount); function burn( uint256 tokenAmount, bool redeemForEth, uint256 minReturn ) external; function getNav() external view returns (uint256); function getBufferBalance() external view returns (uint256); function getFundBalances() external view returns (uint256, uint256); function getWithdrawableAmount(uint256 proxyIndex) external view returns (uint256); function stake( uint256 proxyIndex, uint256 amount, bool force ) external; function updateStakedBalance() external; function unbond(uint256 proxyIndex, bool force) external; function claimUnbonded(uint256 proxyIndex) external; function pauseContract() external; function unpauseContract() external; function emergencyUnbond() external; function emergencyClaim() external; function setFeeDivisors( uint256 mintFeeDivisor, uint256 burnFeeDivisor, uint256 claimFeeDivisor ) external; function updateSwapRouter(SwapMode version) external; function updateUniswapV3AlphaPoolFee(uint24 fee) external; function withdrawNativeToken() external; function withdrawTokenFromProxy(uint256 proxyIndex, address token) external; function withdrawFees() external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IxTokenManager { /** * @dev Add a manager to an xAsset fund */ function addManager(address manager, address fund) external; /** * @dev Remove a manager from an xAsset fund */ function removeManager(address manager, address fund) external; /** * @dev Check if an address is a manager for a fund */ function isManager(address manager, address fund) external view returns (bool); /** * @dev Set revenue controller */ function setRevenueController(address controller) external; /** * @dev Check if address is revenue controller */ function isRevenueController(address caller) external view returns (bool); } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IAlphaStaking { event SetWorker(address worker); event Stake(address owner, uint256 share, uint256 amount); event Unbond(address owner, uint256 unbondTime, uint256 unbondShare); event Withdraw(address owner, uint256 withdrawShare, uint256 withdrawAmount); event CancelUnbond(address owner, uint256 unbondTime, uint256 unbondShare); event Reward(address worker, uint256 rewardAmount); event Extract(address governor, uint256 extractAmount); struct Data { uint256 status; uint256 share; uint256 unbondTime; uint256 unbondShare; } // solhint-disable-next-line func-name-mixedcase function STATUS_READY() external view returns (uint256); // solhint-disable-next-line func-name-mixedcase function STATUS_UNBONDING() external view returns (uint256); // solhint-disable-next-line func-name-mixedcase function UNBONDING_DURATION() external view returns (uint256); // solhint-disable-next-line func-name-mixedcase function WITHDRAW_DURATION() external view returns (uint256); function alpha() external view returns (address); function getStakeValue(address user) external view returns (uint256); function totalAlpha() external view returns (uint256); function totalShare() external view returns (uint256); function stake(uint256 amount) external; function unbond(uint256 share) external; function withdraw() external; function users(address user) external view returns (Data calldata); } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Copied from: // https://github.com/Uniswap/uniswap-v3-periphery/blob/main/contracts/interfaces/ISwapRouter.sol /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3SwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; interface IStakingProxy { function initialize(address alphaStaking) external; function getTotalStaked() external view returns (uint256); function getUnbondingAmount() external view returns (uint256); function getLastUnbondingTimestamp() external view returns (uint256); function getWithdrawableAmount() external view returns (uint256); function isUnbonding() external view returns (bool); function withdraw() external returns (uint256); function stake(uint256 amount) external; function unbond() external; function withdrawToken(address token) external; } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; import "../proxies/StakingProxyBeacon.sol"; import "../proxies/StakingProxyProxy.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract StakingFactory is Ownable { address public stakingProxyBeacon; address payable[] public stakingProxyProxies; constructor(address _stakingProxyBeacon) public { stakingProxyBeacon = _stakingProxyBeacon; } function deployProxy() external onlyOwner returns (address) { StakingProxyProxy proxy = new StakingProxyProxy(stakingProxyBeacon); stakingProxyProxies.push(address(proxy)); return address(proxy); } function getStakingProxyProxiesLength() external view returns (uint256) { return stakingProxyProxies.length; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; interface IOneInchLiquidityProtocol { function swap( address src, address dst, uint256 amount, uint256 minReturn, address referral ) external payable returns (uint256 result); function swapFor( address src, address dst, uint256 amount, uint256 minReturn, address referral, address payable receiver ) external payable returns (uint256 result); } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/proxy/UpgradeableBeacon.sol"; contract StakingProxyBeacon is UpgradeableBeacon { constructor(address _implementation) public UpgradeableBeacon(_implementation) {} } // SPDX-License-Identifier: ISC pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/proxy/BeaconProxy.sol"; contract StakingProxyProxy is BeaconProxy { constructor(address _beacon) public BeaconProxy(_beacon, "") {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IBeacon.sol"; import "../access/Ownable.sol"; import "../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) public { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Proxy.sol"; import "../utils/Address.sol"; import "./IBeacon.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy { /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) public payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _setBeacon(beacon, data); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address beacon) { bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { beacon := sload(slot) } } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_beacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { require( Address.isContract(beacon), "BeaconProxy: beacon is not a contract" ); require( Address.isContract(IBeacon(beacon).implementation()), "BeaconProxy: beacon implementation is not a contract" ); bytes32 slot = _BEACON_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, beacon) } if (data.length > 0) { Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } }
Swap ETH for ALPHA uses either Sushiswap or Uniswap V3 depending on version ethAmount: amount of ETH to swap minReturn: Min return to pass to Uniswap trade return amount of ALPHA returned in the swap These swaps always use 'exact input' - they send exactly the amount specified in arguments to the swap, and the output amount is calculated./ SUSHISWAP UNISWAP V3
function _swapETHforALPHAInternal(uint256 ethAmount, uint256 minReturn) private returns (uint256) { uint256 deadline = MAX_UINT; if (swapMode == SwapMode.SUSHISWAP) { IUniswapV2Router02 routerV2 = IUniswapV2Router02(sushiswapRouter); address[] memory path = new address[](2); path[0] = address(weth); path[1] = address(alphaToken); minReturn, path, address(this), deadline ); return amounts[1]; IUniswapV3SwapRouter routerV3 = IUniswapV3SwapRouter(uniswapRouter); IUniswapV3SwapRouter.ExactInputSingleParams memory params = IUniswapV3SwapRouter.ExactInputSingleParams({ tokenIn: address(weth), tokenOut: address(alphaToken), fee: v3AlphaPoolFee, recipient: address(this), deadline: deadline, amountIn: ethAmount, amountOutMinimum: minReturn, sqrtPriceLimitX96: 0 }); uint256 amountOut = routerV3.exactInputSingle(params); return amountOut; } }
10,295,806
./full_match/80001/0xB9ba12893A838CAaABc2a5E9F6F4fb76DEAc7DAa/sources/src/fancyERC20.sol
Internal function to remove staker from stakers array
function removeStaker(address _staker) internal { for (uint256 i = 0; i < stakers.length; i++) { if (stakers[i] == _staker) { stakers[i] = stakers[stakers.length - 1]; stakers.pop(); break; } } }
5,558,476
pragma solidity >=0.4.24; import '../core/Ownable.sol'; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; contract Ride is Ownable { using SafeMath for uint256; /********************** Public Varables ***********************/ // Contract owner address payable owner; // Placeholder for driver address address payable driverID; // Define a public mapping 'items' that maps the address to a ride. mapping (address => RideItem) items; mapping (address => address) driverRides; mapping (address => Txblocks) itemsHistory; // Set default ride state State constant defaultState = State.None; // Enum contains ride states enum State { None, PassengerRequestRide, DriverAcceptsRide, PassengerConfirmsPickUp, DriverConfirmsDropOff, Canceled } // Struct contains all ride components struct RideItem { address ownerID; // Metamask-Ethereum address of the cBlockPassengerPaymentSentent owner as the product moves through 4 stages address payable driverID; // Metamask-Ethereum address of the driver address payable passengerID; // Metamask-Ethereum address of the rider address rideID; // Ride ID string passengerName; // Passenger name string passengerVehicleRequestType; // Passenger vehicleRequestType string passengerPickUpAddress; // Passenger pickup address string passengerDropOffAddress; // passenger dropoff address string driverVehicleDiscription; // drivers vehicleDiscription uint256 rideDate; // Ride Date: In Epoche uint ridePrice; // Ride Price State rideState; // Ride State as represented in the enum above } // Block number stuct struct Txblocks { uint BlockPassengerPaymentSent; // block ether from passenger to contact uint BlockDriverPaymentSent; // block ether from passenger to driver } /********************** Events ***********************/ event PassengerRequestRide(address rideID); event DriverAcceptsRide(address rideID); event PassengerConfirmsPickUp(address rideID); event DriverConfirmsDropOff(address rideID); event CanceledRide(address rideID); /********************** Modifiers ***********************/ // Define a modifer that checks to see if msg.sender == owner of the contract modifier onlyOwner() { require(msg.sender == owner,"Only contract owner is allowed to call this method"); _; } // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address,"Address is not verified to call this method"); _; } modifier verifyCallerIsRelatedToContract(address _rideID) { require(msg.sender == items[_rideID].driverID || msg.sender == items[_rideID].passengerID,"Address is not verfied to call this method"); _; } // Modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price,"Paid amount is insufficient to cover the price"); _; } // Modifier that checks the price and refunds the remaining balance modifier checkValue(uint _price, address payable addressToFund) { uint amountToReturn = msg.value - _price; addressToFund.transfer(amountToReturn); _; } // Modifier that checks if a passenger can request a new ride modifier hasExistingRide(address _rideID) { require(items[_rideID].rideState != State.DriverAcceptsRide,"Ride needs to be canceled before making a new ride."); require(items[_rideID].rideState != State.PassengerConfirmsPickUp,"Ride needs to be canceled before making a new ride."); _; } modifier isRideCanceled(address _rideID) { require(items[_rideID].rideState != State.Canceled,"Ride has been cancel by passenger"); _; } modifier isRideComplete(address _rideID){ require(items[_rideID].rideState != State.DriverConfirmsDropOff,"This method ride is complete by driver"); _; } // RideItem State Modifiers modifier passengerRequestedRide(address _rideID) { require(items[ _rideID].rideState == State.PassengerRequestRide); _; } modifier driverAcceptedRide(address _rideID) { require(items[ _rideID].rideState == State.DriverAcceptsRide); _; } modifier passengerConfirmedPickUp(address _rideID) { require(items[ _rideID].rideState == State.PassengerConfirmsPickUp); _; } modifier driverConfirmedDropOff(address _rideID) { require(items[ _rideID].rideState == State.DriverConfirmsDropOff); _; } /********************** Constructor & Kill Function ***********************/ constructor() public { // Set contract owner owner = msg.sender; } // Kill function to black Hole the contract function kill() public { if (msg.sender == owner) { address payable ownerAddressPayable = _make_payable(owner); selfdestruct(ownerAddressPayable); } } // allows you to convert an address into a payable address function _make_payable(address x) internal pure returns (address payable) { return address(uint160(x)); } /********************** Ride Functions ***********************/ // Allows for the cancelation of a ride function cancelRide(address _rideID) public payable verifyCallerIsRelatedToContract(_rideID) isRideComplete(_rideID) // check if ride is complete isRideCanceled(_rideID) // check if ride has already been canceled { // 25% cancelation fee goes to driver if (items[ _rideID].rideState == State.PassengerConfirmsPickUp) { items[ _rideID].rideState = State.Canceled; uint256 driverAmount = items[_rideID].ridePrice.mul(2500).div(10000); uint256 remainder = items[_rideID].ridePrice - driverAmount; items[ _rideID].passengerID.transfer(remainder); items[ _rideID].driverID.transfer(driverAmount); driverRides[items[ _rideID].driverID] = address(0x0); emit CanceledRide(_rideID); }else if (items[_rideID].rideState == State.DriverAcceptsRide && msg.sender == items[_rideID].driverID){ items[_rideID].rideState = State.PassengerRequestRide; driverRides[msg.sender] = address(0x0); items[_rideID].driverVehicleDiscription = ""; items[_rideID].driverID = address(0x0); emit PassengerRequestRide(_rideID); }else{ items[ _rideID].rideState = State.Canceled; items[ _rideID].passengerID.transfer(address(this).balance); driverRides[items[ _rideID].driverID] = address(0x0); emit CanceledRide(_rideID); } } /* 1st step in ride share Allows passenger to request a ride with there perfered settings Passenger ether will transfer into contract address until */ function passengerRequestRide( string memory _passengerName, string memory _passengerPickUpAddress, string memory _passengerDropOffAddress, string memory _passengerVehicleRequestType, uint _ridePrice ) public payable hasExistingRide(msg.sender) // Check if passenger has a existing ride paidEnough(_ridePrice) // Check if passenger has paid enough for ride checkValue(_ridePrice, msg.sender) // Check if passenger has over paid { string memory _driverName; // Empty drivers Name string memory _driverVehicleDiscription; // Empty drivers vehicleDiscription RideItem memory newRide; // Create a new struct RideItem in memory newRide.driverID = driverID; // Ethereum address of the driver emtpy for now newRide.rideID = msg.sender; // Ethereum address of the passenger is rideId newRide.passengerID = _make_payable(msg.sender); // Payable ethereum address of the passenger newRide.passengerName = _passengerName; // Passenger Name newRide.passengerPickUpAddress = _passengerPickUpAddress; // Passenger pickup address newRide.passengerDropOffAddress = _passengerDropOffAddress; // Passenger dropoff address newRide.passengerVehicleRequestType = _passengerVehicleRequestType;// Passenger request for specific vehicle newRide.driverVehicleDiscription = _driverVehicleDiscription; // Drive vehicle discription newRide.ridePrice = _ridePrice; // Ride Price newRide.rideDate = now; // Current date & time of ride newRide.rideState = State.PassengerRequestRide; // Ride State as represented in the enum above items[msg.sender] = newRide; // Add newRide to items struct by upc uint placeholder; // Block number place holder Txblocks memory txBlock; // create new txBlock struct txBlock.BlockPassengerPaymentSent = block.number; // add block number txBlock.BlockDriverPaymentSent = placeholder; // assign placeholder values itemsHistory[msg.sender] = txBlock; // add txBlock to itemsHistory mapping by upc // Emit the appropriate event emit PassengerRequestRide(msg.sender); } /* 2nd step in ride share Allows a driver to accept a ride */ function driverAcceptsRide( address _rideID, string memory _driverVehicleDiscription ) public passengerRequestedRide(_rideID) isRideCanceled(_rideID) { driverRides[msg.sender] = _rideID; items[_rideID].rideState = State.DriverAcceptsRide; items[_rideID].driverID = _make_payable(msg.sender); items[_rideID].driverVehicleDiscription = _driverVehicleDiscription; emit DriverAcceptsRide( _rideID); } /* 3rd step in ride share Allows the passenger to confirm the pickup NOTE - passenger is allowed to cancel the ride up to this point, Ether return back to the passenger */ function passengerConfirmsPickUp(address _rideID) public driverAcceptedRide(_rideID) // check items state is for passengerConfirmsPickUp verifyCaller(items[ _rideID].passengerID) isRideCanceled(_rideID) { items[ _rideID].rideState = State.PassengerConfirmsPickUp; // update state emit PassengerConfirmsPickUp( _rideID); } /* 4th step in ride share Allows drive to confirm passenger dropoff Driver will be paid from contract address */ function driverConfirmsDropOff(address _rideID) public passengerConfirmedPickUp(_rideID) verifyCaller(items[_rideID].driverID) // check if same drive as pickup isRideCanceled(_rideID) { // Add block number to history mapping itemsHistory[ _rideID].BlockPassengerPaymentSent = block.number; // Update state items[ _rideID].rideState = State.DriverConfirmsDropOff; // Pay driver from contract items[ _rideID].driverID.transfer(items[_rideID].ridePrice); // Map drivers address to no rideID driverRides[msg.sender] = address(0x0); // Emit related event emit DriverConfirmsDropOff(_rideID); } // allows driver address to get current rideID function fetchDriverBuffer() public view returns (address rideID) { address rideid = driverRides[msg.sender]; return (rideid); } // Define a function 'fetchRideItemBufferOne' that fetches the data /* address passengerID; string passengerName; // Passenger name string passengerVehicleRequestType; // Passenger vehicleRequestType string passengerPickUpAddress; // Passenger pickup address string passengerDropOffAddress; // passenger dropoff address */ function fetchRideItemBufferOne(address _rideID) public view returns //verifyCaller(items[_rideID].passengerID); // only allows the passenger to request there info ( address passengerID, string memory passengerName, string memory passengerVehicleRequestType, string memory passengerPickUpAddress, string memory passengerDropOffAddress ) { // Assign values to the 8 parameters RideItem memory item = items[ _rideID]; return ( item.passengerID, item.passengerName, item.passengerVehicleRequestType, item.passengerPickUpAddress, item.passengerDropOffAddress ); } /* address driverID; // Metamask-Ethereum address of the driver string driverVehicleDiscription; // drivers vehicleDiscription */ function fetchRideItemBufferTwo(address _rideID) public view returns ( address driverID, string memory driverVehicleDiscription ) { // Assign values to the 8 parameters RideItem memory item = items[ _rideID]; return ( item.driverID, item.driverVehicleDiscription ); } /* string rideNotes; // Ride Notes uint256 rideDate; // Ride Date uint ridePrice; // Ride Price State rideState; // Ride State as represented in the enum above */ function fetchRideItemBufferThree(address _rideID) public view returns ( uint256 rideDate, uint ridePrice, State rideState ) { RideItem memory item = items[ _rideID]; return ( item.rideDate, item.ridePrice, item.rideState ); } // Define a function 'fetchRideItemHistory' that fetaches the data function fetchRideItemHistory(address _rideID) public view returns ( uint BlockPassengerToContract, uint BlockContractToDriver ) { // Assign value to the parameters Txblocks memory txblock = itemsHistory[_rideID]; return ( txblock.BlockPassengerPaymentSent, txblock.BlockDriverPaymentSent ); } }
allows driver address to get current rideID
function fetchDriverBuffer() public view returns (address rideID) { address rideid = driverRides[msg.sender]; return (rideid); }
15,797,114
/** Copyright (c) 2018, ZSC Dev Team * 2018-10-19: v0.00.01 */ pragma solidity ^0.4.25; // pragma experimental ABIEncoderV2; import "../common/pausable.sol"; import "../common/delegate.sol"; contract InsuranceCompany { function update(string _key, string _data) external; function remove(string _key) external; function size() external view returns (uint); function getByKey(string _key) external view returns (int, string); function getById(uint _id) external view returns (int, string, string); // function getAll() external view returns (int, string); } contract InsuranceTemplate { function update(string _key, string _data) external; function remove(string _key) external; function size() external view returns (uint); // function getByKey(string _key) external view returns (int, string); function getById(uint _id) external view returns (int, string, string); } contract InsuranceUser { // function add(string _userKey, string _template, string _data) external; // function remove(string _key) external; function size() public view returns (uint); function exist(uint8 _type, string _key0, address _key1) public view returns (bool); // function getByKey(uint8 _type, string _key) external view returns (int, string); function getById(uint8 _type, uint _id) external view returns (int, string); } contract InsurancePolicy { // function add(string _userKey, string _templateKey, string _policyKey, string _data) external; // function addElement(string _key, string _elementKey, string _data) external; // function remove(string _key) external; function size() public view returns (uint); // function getByKey(uint8 _type, string _key) external view returns (int, string); function getById(uint8 _type, uint _id) external view returns (int, string); // function getKeys(uint _id, uint _count) external view returns (int, string); } contract InsuranceIntegral { // function claim(address _account, uint8 _type) public returns (bool); function mint(address _account, uint _value) public returns (bool); // function burn(address _account, uint _value) public; function transfer(address _owner, address _to, uint _value) public returns (bool); function addTrace(address _account, uint8 _scene, uint _time, uint _value, address _from, address _to) public; // function removeTrace(address _account) public; function updateThreshold(uint8 _type, uint _threshold) public; function updateCap(uint _newCap) public; // function trace(address _account, uint _startTime, uint _endTime) public view returns (string); // function traceSize(address _account, uint8 _scene, uint _time) public view returns (uint); function threshold(uint8 _type) public view returns (uint); function cap() public view returns (uint); function totalSupply() public view returns (uint); // function balanceOf(address _owner) public view returns (uint); } contract InsuranceExtension is Pausable, Delegate { address private companyAddr_; address private templateAddr_; address private userAddr_; address private policyAddr_; address private integralAddr_; modifier _checkCompanyAddr() { require(0 != companyAddr_); _; } modifier _checkTemplateAddr() { require(0 != templateAddr_); _; } modifier _checkUserAddr() { require(0 != userAddr_); _; } modifier _checkPolicyAddr() { require(0 != policyAddr_); _; } modifier _checkIntegralAddr() { require(0 != integralAddr_); _; } modifier _onlyAdminOrHigher() { require(checkDelegate(msg.sender, 2)); _; } modifier _onlyReaderOrHigher() { require(checkDelegate(msg.sender, 3)); _; } constructor() public { companyAddr_ = address(0); templateAddr_ = address(0); userAddr_ = address(0); policyAddr_ = address(0); integralAddr_ = address(0); } /** @dev Destroy the contract. */ function destroy() public _onlyOwner { super.kill(); } /** @dev Setup. * @param _companyAddr address The address of template contract. * @param _templateAddr address The address of template contract. * @param _userAddr address The address of user contract. * @param _policyAddr address The address of policy contract. * @param _integralAddr address The address of integral contract. */ function setup(address _companyAddr, address _templateAddr, address _userAddr, address _policyAddr, address _integralAddr) external whenNotPaused _onlyOwner { // check params require(address(0) != _companyAddr); require(address(0) != _templateAddr); require(address(0) != _userAddr); require(address(0) != _policyAddr); require(address(0) != _integralAddr); companyAddr_ = _companyAddr; templateAddr_ = _templateAddr; userAddr_ = _userAddr; policyAddr_ = _policyAddr; integralAddr_ = _integralAddr; } /** @dev called by the owner to pause, triggers stopped state */ function pause() public whenNotPaused _onlyOwner { super.pause(); } /** @dev called by the owner to unpause, returns to normal state */ function unpause() public whenPaused _onlyOwner { super.unpause(); } /** @return true if the contract is paused, false otherwise. */ function paused() public view _onlyOwner returns (bool) { return super.paused(); } /** @dev Update company. * @param _key string The key of company. * @param _data string The data of company. */ function companyUpdate(string _key, string _data) external whenNotPaused _onlyOwner _checkCompanyAddr { InsuranceCompany(companyAddr_).update(_key, _data); } /** @dev Remove company. * @param _key string The key of company. */ function companyRemove(string _key) external whenNotPaused _onlyOwner _checkCompanyAddr { InsuranceCompany(companyAddr_).remove(_key); } /** @dev Get size of company. * @return The size of company. */ function companySize() external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (uint) { return InsuranceCompany(companyAddr_).size(); } /** @dev Get company info by key. * @param _key string The key of company. * @return The error code and the data of template info. * 0: success * -1: params error * -2: no data * -3: no authority * -9: inner error */ function companyGetByKey(string _key) external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (int, string) { return InsuranceCompany(companyAddr_).getByKey(_key); } /** @dev Get company info by id. * @param _id uint The id of company. * @return The error code and the key/data of company. * 0: success * -1: params error * -2: no data * -3: no authority * -9: inner error */ function companyGetById(uint _id) external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (int, string, string) { return InsuranceCompany(companyAddr_).getById(_id); } /** @dev Update template. * @param _key string The key of template. * @param _data string The data of template. */ function templateUpdate(string _key, string _data) external whenNotPaused _onlyOwner _checkTemplateAddr { InsuranceTemplate(templateAddr_).update(_key, _data); } /** @dev Remove template. * @param _key string The key of template. */ function templateRemove(string _key) external whenNotPaused _onlyOwner _checkTemplateAddr { InsuranceTemplate(templateAddr_).remove(_key); } /** @dev Get size of template. * @return The size of template. */ function templateSize() external view whenNotPaused _onlyReaderOrHigher _checkTemplateAddr returns (uint) { return InsuranceTemplate(templateAddr_).size(); } /** @dev Get template info by id. * @param _id uint The id of template. * @return The error code and the key/data of template. * 0: success * -1: params error * -2: no data * -3: no authority * -9: inner error */ function templateGetById(uint _id) external view whenNotPaused _onlyReaderOrHigher _checkTemplateAddr returns (int, string, string) { return InsuranceTemplate(templateAddr_).getById(_id); } /** @dev Get size of users. * @return The size of users. */ function userSize() external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (uint) { return InsuranceUser(userAddr_).size(); } /** @dev Get user info by id. * @param _type uint8 The info type (0: detail, 1: brief). * @param _id uint The id of user. * @return The error code and the JSON data of user info. * 0: success * -1: params error * -2: no data * -3: no authority * -9: inner error */ function userGetById(uint8 _type, uint _id) external view whenNotPaused _onlyReaderOrHigher _checkUserAddr returns (int, string) { return InsuranceUser(userAddr_).getById(_type, _id); } /** @dev Get size of policies. * @return The size of policies. */ function policySize() external view whenNotPaused _onlyReaderOrHigher _checkPolicyAddr returns (uint) { return InsurancePolicy(policyAddr_).size(); } /** @dev Get policy info by id. * @param _type uint8 The info type (0: detail, 1: brief). * @param _id uint The id of policy. * @return The error code and the JSON data of policy info. * 0: success * -1: params error * -2: no data * -3: no authority * -9: inner error */ function policyGetById(uint8 _type, uint _id) external whenNotPaused _onlyReaderOrHigher _checkPolicyAddr view returns (int, string) { return InsurancePolicy(policyAddr_).getById(_type, _id); } /** @dev Mint integrals. * @param _account address The address that will receive the minted integrals. * @param _time uint The trace time(UTC), including TZ and DST. * @param _value uint The amount of integrals to mint. */ function integralMint(address _account, uint _time, uint _value) external whenNotPaused _onlyOwner _checkUserAddr _checkIntegralAddr { require(InsuranceUser(userAddr_).exist(1, "", _account)); if (InsuranceIntegral(integralAddr_).mint(_account, _value)) { InsuranceIntegral(integralAddr_).addTrace(_account, 8, _time, _value, integralAddr_, _account); } } /** @dev Update the threshold of different types of bonus integrals. * @param _type uint8 The types of bonus integrals. * 0: User sign up. * 1: User submit data. * 2: User check in every day. * 3: User invite others. * 4: User share to Wechat. * 5: User share to QQ. * 6: User share to Microblog. * 7: User click advertisements. * @param _threshold uint The threshold of different types of bonus integrals. */ function integralUpdateThreshold(uint8 _type, uint _threshold) external whenNotPaused _onlyOwner _checkIntegralAddr { InsuranceIntegral(integralAddr_).updateThreshold(_type, _threshold); } /** @dev Update cap of integrals. * @param _newCap uint The new cap of integrals. */ function integralUpdateCap(uint _newCap) external whenNotPaused _onlyOwner _checkIntegralAddr { InsuranceIntegral(integralAddr_).updateCap(_newCap); } /** @dev Get the threshold of different types of bonus integrals. * @param _type uint8 The types of bonus integrals. * 0: User sign up. * 1: User submit data. * 2: User check in every day. * 3: User invite others. * 4: User share to Wechat. * 5: User share to QQ. * 6: User share to Microblog. * 7: User click advertisements. * @return The threshold of different types of bonus integrals. */ function integralThreshold(uint8 _type) external view whenNotPaused _onlyOwner _checkIntegralAddr returns (uint) { return InsuranceIntegral(integralAddr_).threshold(_type); } /** @dev Get the cap of integrals. * @return The cap of integrals. */ function integralCap() external view whenNotPaused _onlyOwner _checkIntegralAddr returns (uint) { return InsuranceIntegral(integralAddr_).cap(); } /** @dev Total number of integrals in existence * @return The total number of integrals. */ function integralTotal() external view whenNotPaused _onlyOwner _checkIntegralAddr returns (uint) { return InsuranceIntegral(integralAddr_).totalSupply(); } /** @dev Get contract related address. * @return The addresses of contract related. */ function getAddr() external view whenNotPaused _onlyOwner returns (address, address, address, address, address) { return (companyAddr_, templateAddr_, userAddr_, policyAddr_, integralAddr_); } }
Get size of company. return The size of company./
function companySize() external view whenNotPaused _onlyReaderOrHigher _checkCompanyAddr returns (uint) { return InsuranceCompany(companyAddr_).size(); }
12,868,990
./partial_match/1/0xD53E8E656fB6014E08ef221643D7AB087F6e9289/sources/Token2.sol
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; }
3,627,602
./full_match/56/0x3c8db23fe78Ff17010ba7decf40A619c3eb2d253/sources/project_/contracts/NFTRewardPool.sol
require(_token != address(stakedToken), "!staked");require(_token != address(rewardToken), "!reward");
function inCaseTokensGetStuck(address _token) external onlyOwner { uint256 amount = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(msg.sender, amount); }
3,226,180
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol"; contract CaptureClubNFT is ERC721PresetMinterPauserAutoId { constructor(string memory name, string memory symbol, string memory baseURI) public ERC721PresetMinterPauserAutoId(name, symbol, baseURI) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../access/AccessControl.sol"; import "../utils/Context.sol"; import "../utils/Counters.sol"; import "../token/ERC721/ERC721.sol"; import "../token/ERC721/ERC721Burnable.sol"; import "../token/ERC721/ERC721Pausable.sol"; /** * @dev {ERC721} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * - token ID and URI autogeneration * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable { using Counters for Counters.Counter; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); Counters.Counter private _tokenIdTracker; /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the * account that deploys the contract. * * Token URIs will be autogenerated based on `baseURI` and their token IDs. * See {ERC721-tokenURI}. */ constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setBaseURI(baseURI); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _tokenIdTracker.increment(); } /** * @dev Creates a new token for `to`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI user asssigned based on the base URI passed at construction. * * See {ERC721-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function decentralizedMint(address to, string memory tokenURI) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); // We cannot just use balanceOf to create the new tokenId because tokens // can be burned (destroyed), so we need a separate counter. _mint(to, _tokenIdTracker.current()); _setTokenURI(_tokenIdTracker.current(), tokenURI); _tokenIdTracker.increment(); } /** * @dev Pauses all token transfers. * * See {ERC721Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC721Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause"); _unpause(); } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC721.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ERC721.sol"; import "../../utils/Pausable.sol"; /** * @dev ERC721 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.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.6.2 <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 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: MIT pragma solidity >=0.6.2 <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.6.0 <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.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI user asssigned based on the base URI passed at construction. See {ERC721-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./ We cannot just use balanceOf to create the new tokenId because tokens can be burned (destroyed), so we need a separate counter.
function decentralizedMint(address to, string memory tokenURI) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint"); _mint(to, _tokenIdTracker.current()); _setTokenURI(_tokenIdTracker.current(), tokenURI); _tokenIdTracker.increment(); }
553,280
/* -------------------------------------------------------------------------------- The Bethereum [BETHER] Token Smart Contract Credit: Bethereum Limited ERC20: https://github.com/ethereum/EIPs/issues/20 ERC223: https://github.com/ethereum/EIPs/issues/223 MIT Licence -------------------------------------------------------------------------------- */ /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data) { /* Fix for Mist warning */ _from; _value; _data; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC223Interface { uint public totalSupply; function balanceOf(address who) constant returns (uint); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract BethereumERC223 is ERC223Interface { using SafeMath for uint256; /* Contract Constants */ string public constant _name = "Bethereum"; string public constant _symbol = "BETHER"; uint8 public constant _decimals = 18; /* Contract Variables */ address public owner; mapping(address => uint256) public balances; mapping(address => mapping (address => uint256)) public allowed; /* Constructor initializes the owner's balance and the supply */ function BethereumERC223() { totalSupply = 224181206832398351471266750; owner = msg.sender; } /* ERC20 Events */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed to, uint256 value); /* ERC223 Events */ event Transfer(address indexed from, address indexed to, uint value, bytes data); /* Returns the balance of a particular account */ function balanceOf(address _address) constant returns (uint256 balance) { return balances[_address]; } /* Transfer the balance from the sender's address to the address _to */ function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } else { return false; } } /* Withdraws to address _to form the address _from up to the amount _value */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else { return false; } } /* Allows _spender to withdraw the _allowance amount form sender */ function approve(address _spender, uint256 _allowance) returns (bool success) { allowed[msg.sender][_spender] = _allowance; Approval(msg.sender, _spender, _allowance); return true; } /* Checks how much _spender can withdraw from _owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* ERC223 Functions */ /* Get the contract constant _name */ function name() constant returns (string name) { return _name; } /* Get the contract constant _symbol */ function symbol() constant returns (string symbol) { return _symbol; } /* Get the contract constant _decimals */ function decimals() constant returns (uint8 decimals) { return _decimals; } /* Transfer the balance from the sender's address to the address _to with data _data */ function transfer(address _to, uint _value, bytes _data) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } else { return false; } } /* Transfer function when _to represents a regular address */ function transferToAddress(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Transfer function when _to represents a contract address, with the caveat that the contract needs to implement the tokenFallback function in order to receive tokens */ function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Infers if whether _address is a contract based on the presence of bytecode */ function isContract(address _address) internal returns (bool is_contract) { uint length; if (_address == 0) return false; assembly { length := extcodesize(_address) } if(length > 0) { return true; } else { return false; } } /* Stops any attempt to send Ether to this contract */ function () { throw; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is BethereumERC223, Pausable { function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.transfer(_to, _value, _data); } 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); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is BethereumERC223, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BethereumToken is MintableToken, PausableToken { function BethereumToken(){ pause(); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // amount of raised money in wei 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); function Crowdsale(uint256 _endTime, address _wallet) { require(_endTime >= now); require(_wallet != 0x0); token = createTokenContract(); endTime = _endTime; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (BethereumToken) { return new BethereumToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; bool public weiCapReached = 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); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract BETHERTokenSale is FinalizableCrowdsale { using SafeMath for uint256; // Define sale uint public constant RATE = 17500; uint public constant TOKEN_SALE_LIMIT = 25000 * 1000000000000000000; uint256 public constant TOKENS_FOR_OPERATIONS = 400000000*(10**18); uint256 public constant TOKENS_FOR_SALE = 600000000*(10**18); uint public constant TOKENS_FOR_PRESALE = 315000000*(1 ether / 1 wei); uint public BONUS_PERCENTAGE; enum Phase { Created, CrowdsaleRunning, Paused } Phase public currentPhase = Phase.Created; event LogPhaseSwitch(Phase phase); // Constructor function BETHERTokenSale( uint256 _end, address _wallet ) FinalizableCrowdsale() Crowdsale(_end, _wallet) { } function setNewBonusScheme(uint _bonusPercentage) { BONUS_PERCENTAGE = _bonusPercentage; } function mintRawTokens(address _buyer, uint256 _newTokens) public onlyOwner { token.mint(_buyer, _newTokens); } /// @dev Lets buy you some tokens. function buyTokens(address _buyer) public payable { // Available only if presale or crowdsale is running. require(currentPhase == Phase.CrowdsaleRunning); require(_buyer != address(0)); require(msg.value > 0); require(validPurchase()); uint tokensWouldAddTo = 0; uint weiWouldAddTo = 0; uint256 weiAmount = msg.value; uint newTokens = msg.value.mul(RATE); weiWouldAddTo = weiRaised.add(weiAmount); require(weiWouldAddTo <= TOKEN_SALE_LIMIT); newTokens = addBonusTokens(token.totalSupply(), newTokens); tokensWouldAddTo = newTokens.add(token.totalSupply()); require(tokensWouldAddTo <= TOKENS_FOR_SALE); token.mint(_buyer, newTokens); TokenPurchase(msg.sender, _buyer, weiAmount, newTokens); weiRaised = weiWouldAddTo; forwardFunds(); if (weiRaised == TOKENS_FOR_SALE){ weiCapReached = true; } } // @dev Adds bonus tokens by token supply bought by user // @param _totalSupply total supply of token bought during pre-sale/crowdsale // @param _newTokens tokens currently bought by user function addBonusTokens(uint256 _totalSupply, uint256 _newTokens) internal view returns (uint256) { uint returnTokens; uint tokens = _newTokens; returnTokens = tokens.add(tokens.mul(BONUS_PERCENTAGE).div(100)); return returnTokens; } function setSalePhase(Phase _nextPhase) public onlyOwner { currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function transferTokenOwnership(address _newOwner) { token.transferOwnership(_newOwner); } // Finalize function finalization() internal { uint256 toMint = TOKENS_FOR_OPERATIONS; token.mint(wallet, toMint); token.finishMinting(); token.transferOwnership(wallet); } }
ERC223 Functions / Get the contract constant _name /
function name() constant returns (string name) { return _name; }
20,884
pragma solidity ^0.5.8; contract Ownable { address public owner; event OWNERSHIPTRANSFERRED742(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER252() { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP351(address newOwner) public ONLYOWNER252 { //inject NONSTANDARD NAMING require(newOwner != address(0)); emit OWNERSHIPTRANSFERRED742(owner, newOwner); owner = newOwner; } } contract IERC721 { event TRANSFER592(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVAL116(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL761(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING function BALANCEOF286(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING function OWNEROF883(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING function APPROVE279(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function GETAPPROVED445(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING function SETAPPROVALFORALL429(address operator, bool _approved) public; //inject NONSTANDARD NAMING function ISAPPROVEDFORALL922(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM675(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM377(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING function SAFETRANSFERFROM377(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING } contract ERC20BasicInterface { function TOTALSUPPLY614() public view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF286(address who) public view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER601(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM675(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING event TRANSFER592(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING uint8 public decimals; } contract Bussiness is Ownable { address public ceoAddress = address(0x6C3E879BDD20e9686cfD9BBD1bfD4B2Dd6d47079); IERC721 public erc721Address = IERC721(0x5D00d312e171Be5342067c09BaE883f9Bcb2003B); ERC20BasicInterface public hbwalletToken = ERC20BasicInterface(0xEc7ba74789694d0d03D458965370Dc7cF2FE75Ba); uint256 public ETHFee = 25; // 2,5 % uint256 public Percen = 1000; uint256 public HBWALLETExchange = 21; // cong thuc hbFee = ETHFee / Percen * HBWALLETExchange / 2 uint256 public limitETHFee = 2000000000000000; uint256 public limitHBWALLETFee = 2; uint256 public hightLightFee = 30000000000000000; constructor() public {} struct Price { address payable tokenOwner; uint256 price; uint256 fee; uint256 hbfee; bool isHightlight; } uint[] public arrayTokenIdSale; mapping(uint256 => Price) public prices; modifier ONLYCEOADDRESS253() { //inject NONSTANDARD NAMING require(msg.sender == ceoAddress); _; } // Move the last element to the deleted spot. // Delete the last element, then correct the length. function _BURNARRAYTOKENIDSALE680(uint index) internal { //inject NONSTANDARD NAMING require(index < arrayTokenIdSale.length); arrayTokenIdSale[index] = arrayTokenIdSale[arrayTokenIdSale.length - 1]; delete arrayTokenIdSale[arrayTokenIdSale.length - 1]; arrayTokenIdSale.length--; } function OWNEROF883(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING return erc721Address.OWNEROF883(_tokenId); } function BALANCEOF286() public view returns (uint256){ //inject NONSTANDARD NAMING return address(this).balance; } function GETAPPROVED445(uint256 _tokenId) public view returns (address){ //inject NONSTANDARD NAMING return erc721Address.GETAPPROVED445(_tokenId); } function SETPRICE924(uint256 _tokenId, uint256 _ethPrice, uint256 _ethfee, uint256 _hbfee, bool _isHightLight) internal { //inject NONSTANDARD NAMING prices[_tokenId] = Price(msg.sender, _ethPrice, _ethfee, _hbfee, _isHightLight); arrayTokenIdSale.push(_tokenId); } function SETPRICEFEEETH967(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public payable { //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) { _hightLightFee = hightLightFee; } if (prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; if(prices[_tokenId].price == 0) { if (ethfee >= limitETHFee) { require(msg.value == ethfee + hightLightFee); } else { require(msg.value == limitETHFee + hightLightFee); ethfee = limitETHFee; } } ethfee += prices[_tokenId].fee; } else ethfee = _ethPrice * ETHFee / Percen; SETPRICE924(_tokenId, _ethPrice, ethfee, 0, _isHightLight); } function SETPRICEFEEHBWALLET897(uint256 _tokenId, uint256 _ethPrice, bool _isHightLight) public returns (bool){ //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(_tokenId) == msg.sender && prices[_tokenId].price != _ethPrice); uint256 fee; uint256 ethfee; uint256 _hightLightFee = 0; if (_isHightLight == true && (prices[_tokenId].price == 0 || prices[_tokenId].isHightlight == false)) { _hightLightFee = hightLightFee * HBWALLETExchange / 2 / (10 ** 16); } if (prices[_tokenId].price < _ethPrice) { ethfee = (_ethPrice - prices[_tokenId].price) * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); // ethfee * HBWALLETExchange / 2 * (10 ** 2) / (10 ** 18) if(prices[_tokenId].price == 0) { if (fee >= limitHBWALLETFee) { require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), fee + _hightLightFee)); } else { require(hbwalletToken.TRANSFERFROM675(msg.sender, address(this), limitHBWALLETFee + _hightLightFee)); fee = limitHBWALLETFee; } } fee += prices[_tokenId].hbfee; } else { ethfee = _ethPrice * ETHFee / Percen; fee = ethfee * HBWALLETExchange / 2 / (10 ** 16); } SETPRICE924(_tokenId, _ethPrice, 0, fee, _isHightLight); return true; } function REMOVEPRICE927(uint256 tokenId) public returns (uint256){ //inject NONSTANDARD NAMING require(erc721Address.OWNEROF883(tokenId) == msg.sender); if (prices[tokenId].fee > 0) msg.sender.transfer(prices[tokenId].fee); else if (prices[tokenId].hbfee > 0) hbwalletToken.TRANSFER601(msg.sender, prices[tokenId].hbfee); RESETPRICE775(tokenId); return prices[tokenId].price; } function SETFEE284(uint256 _ethFee, uint256 _HBWALLETExchange, uint256 _hightLightFee) public ONLYOWNER252 returns (uint256, uint256, uint256){ //inject NONSTANDARD NAMING require(_ethFee > 0 && _HBWALLETExchange > 0 && _hightLightFee > 0); ETHFee = _ethFee; HBWALLETExchange = _HBWALLETExchange; hightLightFee = _hightLightFee; return (ETHFee, HBWALLETExchange, hightLightFee); } function SETLIMITFEE654(uint256 _ethlimitFee, uint256 _hbWalletlimitFee) public ONLYOWNER252 returns (uint256, uint256){ //inject NONSTANDARD NAMING require(_ethlimitFee > 0 && _hbWalletlimitFee > 0); limitETHFee = _ethlimitFee; limitHBWALLETFee = _hbWalletlimitFee; return (limitETHFee, limitHBWALLETFee); } function WITHDRAW821(address payable _address, uint256 amount, uint256 _amountHB) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING require(_address != address(0) && amount > 0 && address(this).balance >= amount && _amountHB > 0 && hbwalletToken.BALANCEOF286(address(this)) >= _amountHB); _address.transfer(amount); hbwalletToken.TRANSFERFROM675(address(this), _address, _amountHB); } function CANCELBUSSINESS265() public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING for (uint256 i = 0; i < arrayTokenIdSale.length; i++) { if (prices[arrayTokenIdSale[i]].tokenOwner == erc721Address.OWNEROF883(arrayTokenIdSale[i])) { if (prices[arrayTokenIdSale[i]].fee > 0 && address(this).balance >= prices[arrayTokenIdSale[i]].fee) { prices[arrayTokenIdSale[i]].tokenOwner.transfer(prices[arrayTokenIdSale[i]].fee); } else if (prices[arrayTokenIdSale[i]].hbfee > 0 && hbwalletToken.BALANCEOF286(address(this)) >= prices[arrayTokenIdSale[i]].hbfee) { hbwalletToken.TRANSFER601(prices[arrayTokenIdSale[i]].tokenOwner, prices[arrayTokenIdSale[i]].hbfee); } } RESETPRICE775(arrayTokenIdSale[i]); } } function CHANGECEO557(address _address) public ONLYCEOADDRESS253 { //inject NONSTANDARD NAMING require(_address != address(0)); ceoAddress = _address; } function BUY787(uint256 tokenId) public payable { //inject NONSTANDARD NAMING require(GETAPPROVED445(tokenId) == address(this)); require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); RESETPRICE775(tokenId); } function BUYWITHOUTCHECKAPPROVED538(uint256 tokenId) public payable { //inject NONSTANDARD NAMING require(prices[tokenId].price > 0 && prices[tokenId].price == msg.value); erc721Address.TRANSFERFROM675(prices[tokenId].tokenOwner, msg.sender, tokenId); prices[tokenId].tokenOwner.transfer(msg.value); RESETPRICE775(tokenId); } function RESETPRICE775(uint256 tokenId) private { //inject NONSTANDARD NAMING prices[tokenId] = Price(address(0), 0, 0, 0, false); for (uint256 i = 0; i < arrayTokenIdSale.length; i++) { if (arrayTokenIdSale[i] == tokenId) { _BURNARRAYTOKENIDSALE680(i); } } } }
inject NONSTANDARD NAMING
function _BURNARRAYTOKENIDSALE680(uint index) internal {
7,237,375
./full_match/80001/0xC461989eAF209F43062cCD594994a75D920b5DBA/sources/contracts/dao/ERC1155Dao.sol
mints the token. emits the Mint event. Requirements: ‼ token with `tokenId` must not be already minted. ‼ contract should not be paused. Signature for mint(string,uint256,uint104,uint32,uint48) : `0x3e9047b9` tokenId id of the token. metadataId metadata id of the token. amount amount of the tokens per id. price price of each token. expectedUsageLife expected usage life of the token. expiry expiry of the token./
function mint( uint256 tokenId, string memory metadataId, uint256 amount, uint104 price, uint32 expectedUsageLife, uint48 expiry ) external whenNotPaused { if (_tokenDetails[tokenId].isMinted) revert NotAvailableForOperationLib.NotAvailableForOperation(19); unchecked { _balances[tokenId][address(this)] = amount; _tokenDetails[tokenId] = TokenDetails({ totalSupply: amount, tokenPrice: price, expectedUsageLife: expectedUsageLife, isMinted: true, expireOn: expiry }); _tokenMetadataId[tokenId] = metadataId; } emit Mint(tokenId); }
844,462
pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint256 i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return The reversed value function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint256 i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2**(8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).toBytes32(); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of an input from its scriptsig /// @dev 36 for outpoint, 1 for scriptsig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended script sig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint8 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint8, uint256) { bytes memory _varIntTag = _input.slice(36, 1); uint8 _varIntDataLen = determineVarIntDataLength(_varIntTag); uint256 _len; if (_varIntDataLen == 0) { _len = uint8(_varIntTag[0]); } else { _len = bytesToUint( reverseEndianness(_input.slice(36 + 1, _varIntDataLen)) ); } return (_varIntDataLen, _len); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32 byte tx id with 4 byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32 byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the outpoint index from an input /// @dev 32 byte tx id /// @param _input The input /// @return The tx id (big-endian bytes) function extractInputTxId(bytes memory _input) internal pure returns (bytes32) { bytes memory _leId = abi.encodePacked(extractInputTxIdLE(_input)); bytes memory _beId = reverseEndianness(_leId); return _beId.toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4 byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /// @notice Extracts the tx input index from the input in a tx /// @dev 4 byte tx index /// @param _input The input /// @return The tx index (big-endian uint) function extractTxIndex(bytes memory _input) internal pure returns (uint32) { bytes memory _leIndex = extractTxIndexLE(_input); bytes memory _beIndex = reverseEndianness(_leIndex); return uint32(bytesToUint(_beIndex)); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev 5 types: WPKH, WSH, PKH, SH, and OP_RETURN /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { uint8 _len = uint8(_output.slice(8, 1)[0]); require(_len < 0xfd, "Multi-byte VarInts not supported"); return _len + 8 + 1; // 8 byte value, 1 byte for _len itself } /// @notice Extracts the output at a given index in the TxIns vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { uint256 _len; bytes memory _remaining; uint256 _offset = 1; for (uint8 _i = 0; _i < _index; _i++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); _offset = _offset + _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); return _vout.slice(_offset, _len); } /// @notice Extracts the output script length /// @dev Indexes the length prefix on the pk_script /// @param _output The output /// @return The 1 byte length prefix function extractOutputScriptLen(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(8, 1); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { if (uint8(_output.slice(9, 1)[0]) == 0) { uint256 _len = uint8(extractOutputScriptLen(_output)[0]) - 2; // Check for maliciously formatted witness outputs if (uint8(_output.slice(10, 1)[0]) != uint8(_len)) { return hex""; } return _output.slice(11, _len); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh if ( uint8(_output.slice(11, 1)[0]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac") ) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh if (uint8(_output.slice(_output.length - 1, 1)[0]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and non-standard that don't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _offset = 1; uint8 _nIns = uint8(_vin.slice(0, 1)[0]); // Not valid if it says there are too many or no inputs if (_nIns >= 0xfd || _nIns == 0) { return false; } for (uint8 i = 0; i < _nIns; i++) { // Grab the next input and determine its length. // Increase the offset by that much _offset += determineInputLength( _vin.slice(_offset, _vin.length - _offset) ); // Returns false we jump past the end if (_offset > _vin.length) { return false; } } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted bout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _offset = 1; uint8 _nOuts = uint8(_vout.slice(0, 1)[0]); // Not valid if it says there are too many or no inputs if (_nOuts >= 0xfd || _nOuts == 0) { return false; } for (uint8 i = 0; i < _nOuts; i++) { // Grab the next input and determine its length. // Increase the offset by that much _offset += determineOutputLength( _vout.slice(_offset, _vout.length - _offset) ); // Returns false we jump past the end if (_offset > _vout.length) { return false; } } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (big-endian) function extractMerkleRootBE(bytes memory _header) internal pure returns (bytes memory) { return reverseEndianness(extractMerkleRootLE(_header)); } /// @notice Extracts the target from a block header /// @dev Target is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint256 _exponent = _e - 3; return _mantissa * (256**_exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256 bit number encoded as a 3-byte mantissa and 1 byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (big-endian) function extractPrevBlockBE(bytes memory _header) internal pure returns (bytes memory) { return reverseEndianness(extractPrevBlockLE(_header)); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint256 _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint256 _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint256 i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep( _proof.slice(i * 32, 32), abi.encodePacked(_current) ); } else { _current = _hash256MerkleStep( abi.encodePacked(_current), _proof.slice(i * 32, 32) ); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } }
Extracts the timestamp from a block header Time is not 100% reliable _header The header return The timestamp (little-endian bytes)
function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); }
5,491,251
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ILiquidator { function liquidate( address recipient, address from, address to, uint256 amount, uint256 minOut ) external returns (uint256); function getSwapInfo(address from, address to) external view returns (address router, address[] memory path); function sushiswapRouter() external view returns (address); function uniswapRouter() external view returns (address); function weth() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IManager { function token() external view returns (address); function buybackFee() external view returns (uint256); function managementFee() external view returns (uint256); function liquidators(address from, address to) external view returns (address); function whitelisted(address _contract) external view returns (bool); function banks(uint256 i) external view returns (address); function totalBanks() external view returns (uint256); function strategies(address bank, uint256 i) external view returns (address); function totalStrategies(address bank) external view returns (uint256); function withdrawIndex(address bank) external view returns (uint256); function setWithdrawIndex(uint256 i) external; function rebalance(address bank) external; function finance(address bank) external; function financeAll(address bank) external; function buyback(address from) external; function accrueRevenue( address bank, address underlying, uint256 amount ) external; function exitAll(address bank) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IRegistry { function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ISubscriber { function registry() external view returns (address); function governance() external view returns (address); function manager() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IBankStorage} from "./IBankStorage.sol"; interface IBank is IBankStorage { function strategies(uint256 i) external view returns (address); function totalStrategies() external view returns (uint256); function underlyingBalance() external view returns (uint256); function strategyBalance(uint256 i) external view returns (uint256); function investedBalance() external view returns (uint256); function virtualBalance() external view returns (uint256); function virtualPrice() external view returns (uint256); function pause() external; function unpause() external; function invest(address strategy, uint256 amount) external; function investAll(address strategy) external; function exit(address strategy, uint256 amount) external; function exitAll(address strategy) external; function deposit(uint256 amount) external; function depositFor(uint256 amount, address recipient) external; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IBankStorage { function paused() external view returns (bool); function underlying() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyBase} from "./IStrategyBase.sol"; interface IStrategy is IStrategyBase { function investedBalance() external view returns (uint256); function invest() external; function withdraw(uint256 amount) external returns (uint256); function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IStrategyStorage} from "./IStrategyStorage.sol"; interface IStrategyBase is IStrategyStorage { function underlyingBalance() external view returns (uint256); function derivativeBalance() external view returns (uint256); function rewardBalance() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IStrategyStorage { function bank() external view returns (address); function underlying() external view returns (address); function derivative() external view returns (address); function reward() external view returns (address); // function investedBalance() external view returns (uint256); // function invest() external; // function withdraw(uint256 amount) external returns (uint256); // function withdrawAll() external; } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICompoundStrategyStorage { function comptroller() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library TransferHelper { using SafeERC20 for IERC20; // safely transfer tokens without underflowing function safeTokenTransfer( address recipient, address token, uint256 amount ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 balance = IERC20(token).balanceOf(address(this)); if (balance < amount) { IERC20(token).safeTransfer(recipient, balance); return balance; } else { IERC20(token).safeTransfer(recipient, amount); return amount; } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /// @title Oh! Finance Base Upgradeable /// @notice Contains internal functions to get/set primitive data types used by a proxy contract abstract contract OhUpgradeable { function getAddress(bytes32 slot) internal view returns (address _address) { // solhint-disable-next-line no-inline-assembly assembly { _address := sload(slot) } } function getBoolean(bytes32 slot) internal view returns (bool _bool) { uint256 bool_; // solhint-disable-next-line no-inline-assembly assembly { bool_ := sload(slot) } _bool = bool_ == 1; } function getBytes32(bytes32 slot) internal view returns (bytes32 _bytes32) { // solhint-disable-next-line no-inline-assembly assembly { _bytes32 := sload(slot) } } function getUInt256(bytes32 slot) internal view returns (uint256 _uint) { // solhint-disable-next-line no-inline-assembly assembly { _uint := sload(slot) } } function setAddress(bytes32 slot, address _address) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } function setBytes32(bytes32 slot, bytes32 _bytes32) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _bytes32) } } /// @dev Set a boolean storage variable in a given slot /// @dev Convert to a uint to take up an entire contract storage slot function setBoolean(bytes32 slot, bool _bool) internal { uint256 bool_ = _bool ? 1 : 0; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, bool_) } } function setUInt256(bytes32 slot, uint256 _uint) internal { // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _uint) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ISubscriber} from "../interfaces/ISubscriber.sol"; import {IRegistry} from "../interfaces/IRegistry.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; /// @title Oh! Finance Subscriber Upgradeable /// @notice Base Oh! Finance upgradeable contract used to control access throughout the protocol abstract contract OhSubscriberUpgradeable is Initializable, OhUpgradeable, ISubscriber { bytes32 private constant _REGISTRY_SLOT = 0x1b5717851286d5e98a28354be764b8c0a20eb2fbd059120090ee8bcfe1a9bf6c; /// @notice Only allow authorized addresses (governance or manager) to execute a function modifier onlyAuthorized { require(msg.sender == governance() || msg.sender == manager(), "Subscriber: Only Authorized"); _; } /// @notice Only allow the governance address to execute a function modifier onlyGovernance { require(msg.sender == governance(), "Subscriber: Only Governance"); _; } /// @notice Verify the registry storage slot is correct constructor() { assert(_REGISTRY_SLOT == bytes32(uint256(keccak256("eip1967.subscriber.registry")) - 1)); } /// @notice Initialize the Subscriber /// @param registry_ The Registry contract address /// @dev Always call this method in the initializer function for any derived classes function initializeSubscriber(address registry_) internal initializer { require(Address.isContract(registry_), "Subscriber: Invalid Registry"); _setRegistry(registry_); } /// @notice Set the Registry for the contract. Only callable by Governance. /// @param registry_ The new registry /// @dev Requires sender to be Governance of the new Registry to avoid bricking. /// @dev Ideally should not be used function setRegistry(address registry_) external onlyGovernance { _setRegistry(registry_); require(msg.sender == governance(), "Subscriber: Bad Governance"); } /// @notice Get the Governance address /// @return The current Governance address function governance() public view override returns (address) { return IRegistry(registry()).governance(); } /// @notice Get the Manager address /// @return The current Manager address function manager() public view override returns (address) { return IRegistry(registry()).manager(); } /// @notice Get the Registry address /// @return The current Registry address function registry() public view override returns (address) { return getAddress(_REGISTRY_SLOT); } function _setRegistry(address registry_) private { setAddress(_REGISTRY_SLOT, registry_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IBank} from "../interfaces/bank/IBank.sol"; import {IStrategyBase} from "../interfaces/strategies/IStrategyBase.sol"; import {ILiquidator} from "../interfaces/ILiquidator.sol"; import {IManager} from "../interfaces/IManager.sol"; import {TransferHelper} from "../libraries/TransferHelper.sol"; import {OhSubscriberUpgradeable} from "../registry/OhSubscriberUpgradeable.sol"; import {OhStrategyStorage} from "./OhStrategyStorage.sol"; /// @title Oh! Finance Strategy /// @notice Base Upgradeable Strategy Contract to build strategies on contract OhStrategy is OhSubscriberUpgradeable, OhStrategyStorage, IStrategyBase { using SafeERC20 for IERC20; event Liquidate(address indexed router, address indexed token, uint256 amount); event Sweep(address indexed token, uint256 amount, address recipient); /// @notice Only the Bank can execute these functions modifier onlyBank() { require(msg.sender == bank(), "Strategy: Only Bank"); _; } /// @notice Initialize the base Strategy /// @param registry_ Address of the Registry /// @param bank_ Address of Bank /// @param underlying_ Underying token that is deposited /// @param derivative_ Derivative token received from protocol, or address(0) /// @param reward_ Reward token received from protocol, or address(0) function initializeStrategy( address registry_, address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { initializeSubscriber(registry_); initializeStorage(bank_, underlying_, derivative_, reward_); } /// @dev Balance of underlying awaiting Strategy investment function underlyingBalance() public view override returns (uint256) { return IERC20(underlying()).balanceOf(address(this)); } /// @dev Balance of derivative tokens received from Strategy, if applicable /// @return The balance of derivative tokens function derivativeBalance() public view override returns (uint256) { if (derivative() == address(0)) { return 0; } return IERC20(derivative()).balanceOf(address(this)); } /// @dev Balance of reward tokens awaiting liquidation, if applicable function rewardBalance() public view override returns (uint256) { if (reward() == address(0)) { return 0; } return IERC20(reward()).balanceOf(address(this)); } /// @notice Governance function to sweep any stuck / airdrop tokens to a given recipient /// @param token The address of the token to sweep /// @param amount The amount of tokens to sweep /// @param recipient The address to send the sweeped tokens to function sweep( address token, uint256 amount, address recipient ) external onlyGovernance { // require(!_protected[token], "Strategy: Cannot sweep"); TransferHelper.safeTokenTransfer(recipient, token, amount); emit Sweep(token, amount, recipient); } /// @dev Liquidation function to swap rewards for underlying function liquidate( address from, address to, uint256 amount ) internal { // if (amount > minimumSell()) // find the liquidator to use address manager = manager(); address liquidator = IManager(manager).liquidators(from, to); // increase allowance and liquidate to the manager TransferHelper.safeTokenTransfer(liquidator, from, amount); uint256 received = ILiquidator(liquidator).liquidate(manager, from, to, amount, 1); // notify revenue and transfer proceeds back to strategy IManager(manager).accrueRevenue(bank(), to, received); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IStrategyStorage} from "../interfaces/strategies/IStrategyStorage.sol"; import {OhUpgradeable} from "../proxy/OhUpgradeable.sol"; contract OhStrategyStorage is Initializable, OhUpgradeable, IStrategyStorage { bytes32 internal constant _BANK_SLOT = 0xd2eff96e29993ca5431993c3a205e12e198965c0e1fdd87b4899b57f1e611c74; bytes32 internal constant _UNDERLYING_SLOT = 0x0fad97fe3ec7d6c1e9191a09a0c4ccb7a831b6605392e57d2fedb8501a4dc812; bytes32 internal constant _DERIVATIVE_SLOT = 0x4ff4c9b81c0bf267e01129f4817e03efc0163ee7133b87bd58118a96bbce43d3; bytes32 internal constant _REWARD_SLOT = 0xaeb865605058f37eedb4467ee2609ddec592b0c9a6f7f7cb0db3feabe544c71c; constructor() { assert(_BANK_SLOT == bytes32(uint256(keccak256("eip1967.strategy.bank")) - 1)); assert(_UNDERLYING_SLOT == bytes32(uint256(keccak256("eip1967.strategy.underlying")) - 1)); assert(_DERIVATIVE_SLOT == bytes32(uint256(keccak256("eip1967.strategy.derivative")) - 1)); assert(_REWARD_SLOT == bytes32(uint256(keccak256("eip1967.strategy.reward")) - 1)); } function initializeStorage( address bank_, address underlying_, address derivative_, address reward_ ) internal initializer { _setBank(bank_); _setUnderlying(underlying_); _setDerivative(derivative_); _setReward(reward_); } /// @notice The Bank that the Strategy is associated with function bank() public view override returns (address) { return getAddress(_BANK_SLOT); } /// @notice The underlying token the Strategy invests in AaveV2 function underlying() public view override returns (address) { return getAddress(_UNDERLYING_SLOT); } /// @notice The derivative token received from AaveV2 (aToken) function derivative() public view override returns (address) { return getAddress(_DERIVATIVE_SLOT); } /// @notice The reward token received from AaveV2 (stkAave) function reward() public view override returns (address) { return getAddress(_REWARD_SLOT); } function _setBank(address _address) internal { setAddress(_BANK_SLOT, _address); } function _setUnderlying(address _address) internal { setAddress(_UNDERLYING_SLOT, _address); } function _setDerivative(address _address) internal { setAddress(_DERIVATIVE_SLOT, _address); } function _setReward(address _address) internal { setAddress(_REWARD_SLOT, _address); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IWETH} from "../../interfaces/IWETH.sol"; import {ICToken} from "./interfaces/ICToken.sol"; import {IComptroller} from "./interfaces/IComptroller.sol"; import {ICEther} from "./interfaces/ICEther.sol"; /// @title Oh! Finance Compound Helper /// @notice Helper functions to interact with the Compound Protocol /// @dev https://compound.finance abstract contract OhCompoundHelper { using SafeERC20 for IERC20; /// @notice Get the exchange rate of cTokens => underlying /// @dev https://compound.finance/docs/ctokens#exchange-rate /// @param cToken The cToken address rate to get /// @return The exchange rate scaled by 1e18 function getExchangeRate(address cToken) internal view returns (uint256) { return ICToken(cToken).exchangeRateStored(); } /// @notice Enter the market (approve), required before calling borrow /// @param comptroller The Compound Comptroller (rewards contract) /// @param cToken The cToken market to enter function enter(address comptroller, address cToken) internal { address[] memory cTokens = new address[](1); cTokens[0] = cToken; IComptroller(comptroller).enterMarkets(cTokens); } /// @notice Mint cTokens by providing/lending underlying as collateral /// @param underlying The underlying to lend to Compound /// @param cToken The Compound cToken /// @param amount The amount of underlying to lend function mint( address underlying, address cToken, uint256 amount ) internal { IERC20(underlying).safeIncreaseAllowance(cToken, amount); uint256 result = ICToken(cToken).mint(amount); require(result == 0, "Compound: Borrow failed"); } /// @notice Borrow underlying tokens from a given cToken against collateral /// @param cToken The cToken corresponding the underlying we want to borrow /// @param amount The amount of underlying to borrow function borrow(address cToken, uint256 amount) internal { uint256 result = ICToken(cToken).borrow(amount); require(result == 0, "Compound: Borrow failed"); } /// @notice Repay loan with a given amount of underlying /// @param underlying The underlying to repay /// @param cToken The cToken for the underlying /// @param amount The amount of underlying to repay function repay( address underlying, address cToken, uint256 amount ) internal { IERC20(underlying).safeIncreaseAllowance(cToken, amount); uint256 result = ICToken(cToken).repayBorrow(amount); require(result == 0, "Compound: Repay failed"); } /// @notice Repay loan with weth /// @param weth WETH address /// @param cToken The cToken for the underlying /// @param amount The amount of underlying to repay /// @dev Convert to ETH, then repay function repayInWETH( address weth, address cToken, uint256 amount ) internal { IWETH(weth).withdraw(amount); // Unwrapping ICEther(cToken).repayBorrow{value: amount}(); } /// @notice Redeem cTokens for underlying /// @param cToken The cToken to redeem /// @param amount The amount of cTokens to redeem function redeem(address cToken, uint256 amount) internal { if (amount == 0) { return; } uint256 result = ICToken(cToken).redeem(amount); require(result == 0, "Compound: Redeem cToken"); } /// @notice Redeem cTokens for underlying /// @param cToken The cToken to redeem /// @param amount The amount of underlying tokens to receive function redeemUnderlying(address cToken, uint256 amount) internal { if (amount == 0) { return; } uint256 result = ICToken(cToken).redeemUnderlying(amount); require(result == 0, "Compound: Redeem underlying"); } /// @notice Redeem cTokens for weth /// @param weth WETH Address /// @param cToken The cToken to redeem /// @param amount The amount of underlying to receive /// @dev Redeem in ETH, then convert to weth function redeemUnderlyingInWeth( address weth, address cToken, uint256 amount ) internal { if (amount > 0) { redeemUnderlying(cToken, amount); IWETH(weth).deposit{value: address(this).balance}(); } } /// @notice Claim COMP rewards from Comptroller for this address /// @param comptroller The Compound Comptroller, Reward Contract function claim(address comptroller) internal { IComptroller(comptroller).claimComp(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IStrategy} from "../../interfaces/strategies/IStrategy.sol"; import {TransferHelper} from "../../libraries/TransferHelper.sol"; import {OhStrategy} from "../OhStrategy.sol"; import {OhCompoundHelper} from "./OhCompoundHelper.sol"; import {OhCompoundStrategyStorage} from "./OhCompoundStrategyStorage.sol"; /// @title Oh! Finance Compound Strategy /// @notice Standard, unleveraged strategy. Invest underlying tokens into derivative cTokens /// @dev https://compound.finance/docs/ctokens contract OhCompoundStrategy is IStrategy, OhCompoundHelper, OhStrategy, OhCompoundStrategyStorage { using SafeMath for uint256; using SafeERC20 for IERC20; /// @notice Initialize the Compound Strategy Logic constructor() initializer { assert(registry() == address(0)); assert(bank() == address(0)); assert(underlying() == address(0)); assert(reward() == address(0)); } /// @notice Initializes the Compound Strategy Proxy /// @param registry_ the registry contract /// @param bank_ the bank associated with the strategy /// @param underlying_ the underlying token that is deposited /// @param derivative_ the cToken address received from Compound /// @param reward_ the address of the reward token COMP /// @param comptroller_ the Compound rewards contract /// @dev The function should be called at time of deployment function initializeCompoundStrategy( address registry_, address bank_, address underlying_, address derivative_, address reward_, address comptroller_ ) public initializer { initializeStrategy(registry_, bank_, underlying_, derivative_, reward_); initializeCompoundStorage(comptroller_); IERC20(derivative_).safeApprove(underlying_, type(uint256).max); } /// @notice Get the balance of underlying invested by the Strategy /// @dev Get the exchange rate (which is scaled up by 1e18) and multiply by amount of cTokens /// @return The amount of underlying the strategy has invested function investedBalance() public view override returns (uint256) { uint256 exchangeRate = getExchangeRate(derivative()); return exchangeRate.mul(derivativeBalance()).div(1e18); } function invest() external override onlyBank { _compound(); _deposit(); } function _compound() internal { claim(comptroller()); uint256 amount = rewardBalance(); if (amount > 0) { liquidate(reward(), underlying(), amount); } } // deposit underlying tokens into Compound, minting cTokens function _deposit() internal { uint256 amount = underlyingBalance(); if (amount > 0) { mint(underlying(), derivative(), amount); } } // withdraw all underlying by redeem all cTokens function withdrawAll() external override onlyBank { uint256 invested = investedBalance(); _withdraw(msg.sender, invested); } // withdraw an amount of underlying tokens function withdraw(uint256 amount) external override onlyBank returns (uint256) { uint256 withdrawn = _withdraw(msg.sender, amount); return withdrawn; } // withdraw underlying tokens from the protocol after redeeming them from compound function _withdraw(address recipient, uint256 amount) internal returns (uint256) { if (amount == 0) { return 0; } // calculate amount of shares to redeem uint256 invested = investedBalance(); uint256 supplyShare = amount.mul(1e18).div(invested); uint256 redeemAmount = supplyShare.mul(invested).div(1e18); // safely redeem from Compound if (redeemAmount > invested) { redeemUnderlying(derivative(), invested); } else { redeemUnderlying(derivative(), redeemAmount); } // withdraw to bank uint256 withdrawn = TransferHelper.safeTokenTransfer(recipient, underlying(), amount); return withdrawn; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {ICompoundStrategyStorage} from "../../interfaces/strategies/compound/ICompoundStrategyStorage.sol"; import {OhUpgradeable} from "../../proxy/OhUpgradeable.sol"; contract OhCompoundStrategyStorage is Initializable, OhUpgradeable, ICompoundStrategyStorage { bytes32 internal constant _COMPTROLLER_SLOT = 0x5afedb916735b48cdf292f42c56bdd9f2c18a47029ac6473a9597ce1cb6a8661; constructor() { assert(_COMPTROLLER_SLOT == bytes32(uint256(keccak256("eip1967.compoundStrategy.comptroller")) - 1)); } function initializeCompoundStorage(address comptroller_) internal initializer { _setComptroller(comptroller_); } function comptroller() public view override returns (address) { return getAddress(_COMPTROLLER_SLOT); } function _setComptroller(address comptroller_) internal { setAddress(_COMPTROLLER_SLOT, comptroller_); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOfUnderlying(address account) external returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface ICToken { function underlying() external; function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; interface IComptroller { function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint256 redeemTokens, uint256 borrowAmount ) external view returns ( uint256, uint256, uint256 ); function claimComp(address holder) external; function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); }
Claim COMP rewards from Comptroller for this address comptroller The Compound Comptroller, Reward Contract
function claim(address comptroller) internal { IComptroller(comptroller).claimComp(address(this)); }
13,655,234
./full_match/43114/0xD97B4D013b31df04b6917Dc318D3197169c36bFD/sources/contracts/LongShort.sol
Sets a market as active once it has already been setup by createNewSyntheticMarket. Seperated from createNewSyntheticMarket due to gas considerations. marketIndex An int32 which uniquely identifies the market. kInitialMultiplier Linearly decreasing multiplier for Float token issuance for the market when staking synths. kPeriod Time which kInitialMultiplier will last unstakeFee_e18 Base 1e18 percentage fee levied when unstaking for the market. balanceIncentiveCurve_exponent Sets the degree to which Float token issuance differs for market sides in unbalanced markets. See Staker.sol balanceIncentiveCurve_equilibriumOffset An offset to account for naturally imbalanced markets when Float token issuance should differ for market sides. See Staker.sol initialMarketSeedForEachMarketSide Amount of payment token that will be deposited in each market side to seed the market. Set this value to one initially - 0 is a null value and thus potentially bug prone. Add new staker funds with fresh synthetic tokens.
function initializeMarket( uint32 marketIndex, uint256 kInitialMultiplier, uint256 kPeriod, uint256 unstakeFee_e18, uint256 initialMarketSeedForEachMarketSide, uint256 balanceIncentiveCurve_exponent, int256 balanceIncentiveCurve_equilibriumOffset, uint256 _marketTreasurySplitGradient_e18, uint256 marketLeverage ) external adminOnly { require( kInitialMultiplier != 0 && unstakeFee_e18 != 0 && initialMarketSeedForEachMarketSide != 0 && balanceIncentiveCurve_exponent != 0 && _marketTreasurySplitGradient_e18 != 0 ); require(!marketExists[marketIndex], "already initialized"); require(marketIndex <= latestMarket, "index too high"); marketExists[marketIndex] = true; marketTreasurySplitGradient_e18[marketIndex] = _marketTreasurySplitGradient_e18; marketUpdateIndex[marketIndex] = 1; _seedMarketInitially(initialMarketSeedForEachMarketSide, marketIndex); require(marketLeverage <= 50e18 && marketLeverage >= 1e17, "Incorrect leverage"); marketLeverage_e18[marketIndex] = marketLeverage; IStaker(staker).addNewStakingFund( marketIndex, syntheticTokens[marketIndex][true], syntheticTokens[marketIndex][false], kInitialMultiplier, kPeriod, unstakeFee_e18, balanceIncentiveCurve_exponent, balanceIncentiveCurve_equilibriumOffset ); IStaker(staker).pushUpdatedMarketPricesToUpdateFloatIssuanceCalculations( marketIndex, 1, 1e18, 1e18, initialMarketSeedForEachMarketSide, initialMarketSeedForEachMarketSide ); emit NewMarketLaunchedAndSeeded( marketIndex, initialMarketSeedForEachMarketSide, marketLeverage ); } ╚══════════════════════════════╝*/
4,519,949
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title PullPayment * @dev Base contract supporting async send for pull payments. Inherit from this * contract and use asyncSend instead of send. */ contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; /** * @dev Called by the payer to store the sent amount as credit to be pulled. * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } /** * @dev withdraw accumulated balance, called by payee. */ function withdrawPayments() { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(this.balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; assert(payee.send(payment)); } } contract TrivialToken is StandardToken, PullPayment { //Constants uint8 constant DECIMALS = 0; uint256 constant MIN_ETH_AMOUNT = 0.005 ether; uint256 constant MIN_BID_PERCENTAGE = 10; uint256 constant TOTAL_SUPPLY = 1000000; uint256 constant TOKENS_PERCENTAGE_FOR_KEY_HOLDER = 25; uint256 constant CLEANUP_DELAY = 180 days; uint256 constant FREE_PERIOD_DURATION = 60 days; //Basic string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; //Accounts address public artist; address public trivial; //Time information uint256 public icoDuration; uint256 public icoEndTime; uint256 public auctionDuration; uint256 public auctionEndTime; uint256 public freePeriodEndTime; //Token information uint256 public tokensForArtist; uint256 public tokensForTrivial; uint256 public tokensForIco; //ICO and auction results uint256 public amountRaised; address public highestBidder; uint256 public highestBid; bytes32 public auctionWinnerMessageHash; uint256 public nextContributorIndexToBeGivenTokens; uint256 public tokensDistributedToContributors; //Events event IcoStarted(uint256 icoEndTime); event IcoContributed(address contributor, uint256 amountContributed, uint256 amountRaised); event IcoFinished(uint256 amountRaised); event IcoCancelled(); event AuctionStarted(uint256 auctionEndTime); event HighestBidChanged(address highestBidder, uint256 highestBid); event AuctionFinished(address highestBidder, uint256 highestBid); event WinnerProvidedHash(); //State enum State { Created, IcoStarted, IcoFinished, AuctionStarted, AuctionFinished, IcoCancelled } State public currentState; //Item description struct DescriptionHash { bytes32 descriptionHash; uint256 timestamp; } DescriptionHash public descriptionHash; DescriptionHash[] public descriptionHashHistory; //Token contributors and holders mapping(address => uint) public contributions; address[] public contributors; //Modififers modifier onlyInState(State expectedState) { require(expectedState == currentState); _; } modifier onlyBefore(uint256 _time) { require(now < _time); _; } modifier onlyAfter(uint256 _time) { require(now > _time); _; } modifier onlyTrivial() { require(msg.sender == trivial); _; } modifier onlyArtist() { require(msg.sender == artist); _; } modifier onlyAuctionWinner() { require(currentState == State.AuctionFinished); require(msg.sender == highestBidder); _; } function TrivialToken( string _name, string _symbol, uint256 _icoDuration, uint256 _auctionDuration, address _artist, address _trivial, uint256 _tokensForArtist, uint256 _tokensForTrivial, uint256 _tokensForIco, bytes32 _descriptionHash ) { /*require( TOTAL_SUPPLY == SafeMath.add( _tokensForArtist, SafeMath.add(_tokensForTrivial, _tokensForIco) ) );*/ require(MIN_BID_PERCENTAGE < 100); require(TOKENS_PERCENTAGE_FOR_KEY_HOLDER < 100); name = _name; symbol = _symbol; decimals = DECIMALS; icoDuration = _icoDuration; auctionDuration = _auctionDuration; artist = _artist; trivial = _trivial; tokensForArtist = _tokensForArtist; tokensForTrivial = _tokensForTrivial; tokensForIco = _tokensForIco; descriptionHash = DescriptionHash(_descriptionHash, now); currentState = State.Created; } /* ICO methods */ function startIco() onlyInState(State.Created) onlyTrivial() { icoEndTime = SafeMath.add(now, icoDuration); freePeriodEndTime = SafeMath.add(icoEndTime, FREE_PERIOD_DURATION); currentState = State.IcoStarted; IcoStarted(icoEndTime); } function contributeInIco() payable onlyInState(State.IcoStarted) onlyBefore(icoEndTime) { require(msg.value > MIN_ETH_AMOUNT); if (contributions[msg.sender] == 0) { contributors.push(msg.sender); } contributions[msg.sender] = SafeMath.add(contributions[msg.sender], msg.value); amountRaised = SafeMath.add(amountRaised, msg.value); IcoContributed(msg.sender, msg.value, amountRaised); } function distributeTokens(uint256 contributorsNumber) onlyInState(State.IcoStarted) onlyAfter(icoEndTime) { for (uint256 i = 0; i < contributorsNumber && nextContributorIndexToBeGivenTokens < contributors.length; ++i) { address currentContributor = contributors[nextContributorIndexToBeGivenTokens++]; uint256 tokensForContributor = SafeMath.div( SafeMath.mul(tokensForIco, contributions[currentContributor]), amountRaised // amountRaised can&#39;t be 0, ICO is cancelled then ); balances[currentContributor] = tokensForContributor; tokensDistributedToContributors = SafeMath.add(tokensDistributedToContributors, tokensForContributor); } } function finishIco() onlyInState(State.IcoStarted) onlyAfter(icoEndTime) { if (amountRaised == 0) { currentState = State.IcoCancelled; return; } // all contributors must have received their tokens to finish ICO require(nextContributorIndexToBeGivenTokens >= contributors.length); balances[artist] = SafeMath.add(balances[artist], tokensForArtist); balances[trivial] = SafeMath.add(balances[trivial], tokensForTrivial); uint256 leftovers = SafeMath.sub(tokensForIco, tokensDistributedToContributors); balances[artist] = SafeMath.add(balances[artist], leftovers); if (!artist.send(this.balance)) { asyncSend(artist, this.balance); } currentState = State.IcoFinished; IcoFinished(amountRaised); } function checkContribution(address contributor) constant returns (uint) { return contributions[contributor]; } /* Auction methods */ function canStartAuction() returns (bool) { bool isArtist = msg.sender == artist; bool isKeyHolder = balances[msg.sender] >= SafeMath.div( SafeMath.mul(TOTAL_SUPPLY, TOKENS_PERCENTAGE_FOR_KEY_HOLDER), 100); return isArtist || isKeyHolder; } function startAuction() onlyAfter(freePeriodEndTime) onlyInState(State.IcoFinished) { require(canStartAuction()); // 100% tokens owner is the only key holder if (balances[msg.sender] == TOTAL_SUPPLY) { // no auction takes place, highestBidder = msg.sender; currentState = State.AuctionFinished; AuctionFinished(highestBidder, highestBid); return; } auctionEndTime = SafeMath.add(now, auctionDuration); currentState = State.AuctionStarted; AuctionStarted(auctionEndTime); } function bidInAuction() payable onlyInState(State.AuctionStarted) onlyBefore(auctionEndTime) { //Must be greater or equal to minimal amount require(msg.value >= MIN_ETH_AMOUNT); uint256 bid = calculateUserBid(); //If there was a bid already if (highestBid >= MIN_ETH_AMOUNT) { //Must be greater or equal to 105% of previous bid uint256 minimalOverBid = SafeMath.add(highestBid, SafeMath.div( SafeMath.mul(highestBid, MIN_BID_PERCENTAGE), 100 )); require(bid >= minimalOverBid); //Return to previous bidder his balance //Value to return: current balance - current bid - paymentsInAsyncSend uint256 amountToReturn = SafeMath.sub(SafeMath.sub( this.balance, msg.value ), totalPayments); if (!highestBidder.send(amountToReturn)) { asyncSend(highestBidder, amountToReturn); } } highestBidder = msg.sender; highestBid = bid; HighestBidChanged(highestBidder, highestBid); } function calculateUserBid() private returns (uint256) { uint256 bid = msg.value; uint256 contribution = balanceOf(msg.sender); if (contribution > 0) { //Formula: (sentETH * allTokens) / (allTokens - userTokens) //User sends 16ETH, has 40 of 200 tokens //(16 * 200) / (200 - 40) => 3200 / 160 => 20 bid = SafeMath.div( SafeMath.mul(msg.value, TOTAL_SUPPLY), SafeMath.sub(TOTAL_SUPPLY, contribution) ); } return bid; } function finishAuction() onlyInState(State.AuctionStarted) onlyAfter(auctionEndTime) { require(highestBid > 0); // auction cannot be finished until at least one person bids currentState = State.AuctionFinished; AuctionFinished(highestBidder, highestBid); } function withdrawShares(address holder) public onlyInState(State.AuctionFinished) { uint256 availableTokens = balances[holder]; require(availableTokens > 0); balances[holder] = 0; if (holder != highestBidder) { holder.transfer( SafeMath.div(SafeMath.mul(highestBid, availableTokens), TOTAL_SUPPLY) ); } } function isKeyHolder(address person) constant returns (bool) { return balances[person] >= SafeMath.div(tokensForIco, TOKENS_PERCENTAGE_FOR_KEY_HOLDER); } /* General methods */ function contributorsCount() constant returns (uint256) { return contributors.length; } // Cancel ICO will be redesigned to prevent // risk of user funds overtaken /*function cancelIco() onlyInState(State.IcoStarted) onlyTrivial() { currentState = State.IcoCancelled; IcoCancelled(); } function claimIcoContribution(address contributor) onlyInState(State.IcoCancelled) { uint256 contribution = contributions[contributor]; require(contribution > 0); contributions[contributor] = 0; contributor.transfer(contribution); }*/ function setDescriptionHash(bytes32 _descriptionHash) onlyArtist() { descriptionHashHistory.push(descriptionHash); descriptionHash = DescriptionHash(_descriptionHash, now); } function setAuctionWinnerMessageHash(bytes32 _auctionWinnerMessageHash) onlyAuctionWinner() { auctionWinnerMessageHash = _auctionWinnerMessageHash; WinnerProvidedHash(); } function killContract() onlyTrivial() { require( ( currentState == State.AuctionFinished && now > SafeMath.add(auctionEndTime, CLEANUP_DELAY) // Delay in correct state ) || currentState == State.IcoCancelled // No delay in cancelled state ); selfdestruct(trivial); } // helper function to avoid too many contract calls on frontend side function getContractState() constant returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, State, uint256, uint256, uint256 ) { return ( icoEndTime, auctionDuration, auctionEndTime, tokensForArtist, tokensForTrivial, tokensForIco, amountRaised, highestBidder, highestBid, currentState, TOKENS_PERCENTAGE_FOR_KEY_HOLDER, MIN_BID_PERCENTAGE, freePeriodEndTime ); } function transfer(address _to, uint _value) onlyInState(State.IcoFinished) returns (bool) { return BasicToken.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) onlyInState(State.IcoFinished) returns (bool) { return StandardToken.transferFrom(_from, _to, _value); } function () payable { if (currentState == State.IcoStarted) { contributeInIco(); } else if (currentState == State.AuctionStarted) { bidInAuction(); } else { revert(); } } }
100% tokens owner is the only key holder no auction takes place,
function startAuction() onlyAfter(freePeriodEndTime) onlyInState(State.IcoFinished) { require(canStartAuction()); if (balances[msg.sender] == TOTAL_SUPPLY) { highestBidder = msg.sender; currentState = State.AuctionFinished; AuctionFinished(highestBidder, highestBid); return; } auctionEndTime = SafeMath.add(now, auctionDuration); currentState = State.AuctionStarted; AuctionStarted(auctionEndTime); }
2,030,908
pragma solidity ^0.4.19; /** * * @title McFly.aero - main contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" * */ /** * @title ERC20 Basic smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ 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 Ownable smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public candidate; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to _request_ transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function requestOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); candidate = newOwner; } /** * @dev Allows the _NEW_ candidate to complete transfer control of the contract to him. */ function confirmOwnership() public { require(candidate == msg.sender); owner = candidate; OwnershipTransferred(owner, candidate); } } /** * @title MultiOwners smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() public { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() constant public returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) constant public returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner public { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner public { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } /** * @title SafeMath * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title BasicToken smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @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 * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <[email protected]>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title McFly token smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract McFlyToken is MintableToken { string public constant name = "McFlyToken"; string public constant symbol = "McFLY"; uint8 public constant decimals = 18; /// @dev mapping for whitelist mapping(address=>bool) whitelist; /// @dev event throw when allowed to transfer address added to whitelist /// @param from address event AllowTransfer(address from); /// @dev check for allowence of transfer modifier canTransfer() { require(mintingFinished || whitelist[msg.sender]); _; } /// @dev add address to whitelist /// @param from address to add function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); } /// @dev Do the transfer from address to address value /// @param from address from /// @param to address to /// @param value uint256 function transferFrom(address from, address to, uint256 value) canTransfer public returns (bool) { return super.transferFrom(from, to, value); } /// @dev Do the transfer from token address to "to" address value /// @param to address to /// @param value uint256 value function transfer(address to, uint256 value) canTransfer public returns (bool) { return super.transfer(to, value); } } /** * @title Haltable smart contract - controls owner access * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract Haltable is MultiOwners { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } /// @dev called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } /// @dev called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /** * @title McFly crowdsale smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" * @dev inherited from MultiOwners & Haltable */ contract McFlyCrowd is MultiOwners, Haltable { using SafeMath for uint256; /// @dev Total ETH received during WAVES, TLP1.2 & window[1-5] uint256 public counter_in; // tlp2 /// @dev minimum ETH to partisipate in window 1-5 uint256 public minETHin = 1e18; // 1 ETH /// @dev Token McFlyToken public token; /// @dev Withdraw wallet address public wallet; /// @dev start and end timestamp for TLP 1.2, other values callculated uint256 public sT2; // startTimeTLP2 uint256 constant dTLP2 = 118 days; // days of TLP2 uint256 constant dBt = 60 days; // days between Windows uint256 constant dW = 12 days; // 12 days for 3,4,5,6,7 windows; /// @dev Cap maximum possible tokens for minting uint256 public constant hardCapInTokens = 1800e24; // 1,800,000,000 MFL /// @dev maximum possible tokens for sell uint256 public constant mintCapInTokens = 1260e24; // 1,260,000,000 MFL /// @dev tokens crowd within TLP2 uint256 public crowdTokensTLP2; uint256 public _preMcFly; /// @dev maximum possible tokens for fund minting uint256 constant fundTokens = 270e24; // 270,000,000 MFL uint256 public fundTotalSupply; address public fundMintingAgent; /// @dev maximum possible tokens to convert from WAVES uint256 constant wavesTokens = 100e24; // 100,000,000 MFL address public wavesAgent; address public wavesGW; /// @dev Vesting param for team, advisory, reserve. uint256 constant VestingPeriodInSeconds = 30 days; // 24 month uint256 constant VestingPeriodsCount = 24; /// @dev Team 10% uint256 constant _teamTokens = 180e24; uint256 public teamTotalSupply; address public teamWallet; /// @dev Bounty 5% (2% + 3%) /// @dev Bounty online 2% uint256 constant _bountyOnlineTokens = 36e24; address public bountyOnlineWallet; address public bountyOnlineGW; /// @dev Bounty offline 3% uint256 constant _bountyOfflineTokens = 54e24; address public bountyOfflineWallet; /// @dev Advisory 5% uint256 constant _advisoryTokens = 90e24; uint256 public advisoryTotalSupply; address public advisoryWallet; /// @dev Reserved for future 9% uint256 constant _reservedTokens = 162e24; uint256 public reservedTotalSupply; address public reservedWallet; /// @dev AirDrop 1% uint256 constant _airdropTokens = 18e24; address public airdropWallet; address public airdropGW; /// @dev PreMcFly wallet (MFL) address public preMcFlyWallet; /// @dev Ppl structure for Win1-5 struct Ppl { address addr; uint256 amount; } mapping (uint32 => Ppl) public ppls; /// @dev Window structure for Win1-5 struct Window { bool active; uint256 totalEthInWindow; uint32 totalTransCnt; uint32 refundIndex; uint256 tokenPerWindow; } mapping (uint8 => Window) public ww; /// @dev Events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenPurchaseInWindow(address indexed beneficiary, uint256 value, uint8 winnum, uint32 totalcnt, uint256 totaleth1); event TransferOddEther(address indexed beneficiary, uint256 value); event FundMinting(address indexed beneficiary, uint256 value); event WithdrawVesting(address indexed beneficiary, uint256 period, uint256 value, uint256 valueTotal); event TokenWithdrawAtWindow(address indexed beneficiary, uint256 value); event SetFundMintingAgent(address newAgent); event SetTeamWallet(address newTeamWallet); event SetAdvisoryWallet(address newAdvisoryWallet); event SetReservedWallet(address newReservedWallet); event SetStartTimeTLP2(uint256 newStartTimeTLP2); event SetMinETHincome(uint256 newMinETHin); event NewWindow(uint8 winNum, uint256 amountTokensPerWin); event TokenETH(uint256 totalEth, uint32 totalCnt); /// @dev check for Non zero value modifier validPurchase() { require(msg.value != 0); _; } /** * @dev conctructor of contract, set main params, create new token, do minting for some wallets * @param _startTimeTLP2 - set date time of starting of TLP2 (main date!) * @param _preMcFlyTotalSupply - set amount in wei total supply of previouse contract (MFL) * @param _wallet - wallet for transfer ETH to it * @param _wavesAgent - wallet for WAVES gw * @param _wavesGW - wallet for WAVES gw * @param _fundMintingAgent - wallet who allowed to mint before TLP2 * @param _teamWallet - wallet for team vesting * @param _bountyOnlineWallet - wallet for online bounty * @param _bountyOnlineGW - wallet for online bounty GW * @param _bountyOfflineWallet - wallet for offline bounty * @param _advisoryWallet - wallet for advisory vesting * @param _reservedWallet - wallet for reserved vesting * @param _airdropWallet - wallet for airdrop * @param _airdropGW - wallet for airdrop GW * @param _preMcFlyWallet - wallet for transfer old MFL->McFly (once) */ function McFlyCrowd( uint256 _startTimeTLP2, uint256 _preMcFlyTotalSupply, address _wallet, address _wavesAgent, address _wavesGW, address _fundMintingAgent, address _teamWallet, address _bountyOnlineWallet, address _bountyOnlineGW, address _bountyOfflineWallet, address _advisoryWallet, address _reservedWallet, address _airdropWallet, address _airdropGW, address _preMcFlyWallet ) public { require(_startTimeTLP2 >= block.timestamp); require(_preMcFlyTotalSupply > 0); require(_wallet != 0x0); require(_wavesAgent != 0x0); require(_wavesGW != 0x0); require(_fundMintingAgent != 0x0); require(_teamWallet != 0x0); require(_bountyOnlineWallet != 0x0); require(_bountyOnlineGW != 0x0); require(_bountyOfflineWallet != 0x0); require(_advisoryWallet != 0x0); require(_reservedWallet != 0x0); require(_airdropWallet != 0x0); require(_airdropGW != 0x0); require(_preMcFlyWallet != 0x0); token = new McFlyToken(); wallet = _wallet; sT2 = _startTimeTLP2; wavesAgent = _wavesAgent; wavesGW = _wavesGW; fundMintingAgent = _fundMintingAgent; teamWallet = _teamWallet; bountyOnlineWallet = _bountyOnlineWallet; bountyOnlineGW = _bountyOnlineGW; bountyOfflineWallet = _bountyOfflineWallet; advisoryWallet = _advisoryWallet; reservedWallet = _reservedWallet; airdropWallet = _airdropWallet; airdropGW = _airdropGW; preMcFlyWallet = _preMcFlyWallet; /// @dev Mint all tokens and than control it by vesting _preMcFly = _preMcFlyTotalSupply; token.mint(preMcFlyWallet, _preMcFly); // McFly for thansfer to old MFL owners token.allowTransfer(preMcFlyWallet); crowdTokensTLP2 = crowdTokensTLP2.add(_preMcFly); token.mint(wavesAgent, wavesTokens); // 100,000,000 MFL token.allowTransfer(wavesAgent); token.allowTransfer(wavesGW); crowdTokensTLP2 = crowdTokensTLP2.add(wavesTokens); token.mint(this, _teamTokens); // mint to contract address token.mint(bountyOnlineWallet, _bountyOnlineTokens); token.allowTransfer(bountyOnlineWallet); token.allowTransfer(bountyOnlineGW); token.mint(bountyOfflineWallet, _bountyOfflineTokens); token.allowTransfer(bountyOfflineWallet); token.mint(this, _advisoryTokens); token.mint(this, _reservedTokens); token.mint(airdropWallet, _airdropTokens); token.allowTransfer(airdropWallet); token.allowTransfer(airdropGW); } /** * @dev check is TLP2 is active? * @return false if crowd TLP2 event was ended */ function withinPeriod() constant public returns (bool) { return (now >= sT2 && now <= (sT2+dTLP2)); } /** * @dev check is TLP2 is active and minting Not finished * @return false if crowd event was ended */ function running() constant public returns (bool) { return withinPeriod() && !token.mintingFinished(); } /** * @dev check current stage name * @return uint8 stage number */ function stageName() constant public returns (uint8) { uint256 eT2 = sT2+dTLP2; if (now < sT2) {return 101;} // not started if (now >= sT2 && now <= eT2) {return (102);} // TLP1.2 if (now > eT2 && now < eT2+dBt) {return (103);} // preTLP1.3 if (now >= (eT2+dBt) && now <= (eT2+dBt+dW)) {return (0);} // TLP1.3 if (now > (eT2+dBt+dW) && now < (eT2+dBt+dW+dBt)) {return (104);} // preTLP1.4 if (now >= (eT2+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW)) {return (1);} // TLP1.4 if (now > (eT2+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt)) {return (105);} // preTLP1.5 if (now >= (eT2+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW)) {return (2);} // TLP1.5 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (106);} // preTLP1.6 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (3);} // TLP1.6 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (107);} // preTLP1.7 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (4);} // TLP1.7" if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (200);} // Finished return (201); // unknown } /** * @dev change agent for minting * @param agent - new agent address */ function setFundMintingAgent(address agent) onlyOwner public { fundMintingAgent = agent; SetFundMintingAgent(agent); } /** * @dev change wallet for team vesting (this make possible to set smart-contract address later) * @param _newTeamWallet - new wallet address */ function setTeamWallet(address _newTeamWallet) onlyOwner public { teamWallet = _newTeamWallet; SetTeamWallet(_newTeamWallet); } /** * @dev change wallet for advisory vesting (this make possible to set smart-contract address later) * @param _newAdvisoryWallet - new wallet address */ function setAdvisoryWallet(address _newAdvisoryWallet) onlyOwner public { advisoryWallet = _newAdvisoryWallet; SetAdvisoryWallet(_newAdvisoryWallet); } /** * @dev change wallet for reserved vesting (this make possible to set smart-contract address later) * @param _newReservedWallet - new wallet address */ function setReservedWallet(address _newReservedWallet) onlyOwner public { reservedWallet = _newReservedWallet; SetReservedWallet(_newReservedWallet); } /** * @dev change min ETH income during Window1-5 * @param _minETHin - new limit */ function setMinETHin(uint256 _minETHin) onlyOwner public { minETHin = _minETHin; SetMinETHincome(_minETHin); } /** * @dev set TLP1.X (2-7) start & end dates * @param _at - new or old start date */ function setStartEndTimeTLP(uint256 _at) onlyOwner public { require(block.timestamp < sT2); // forbid change time when TLP1.2 is active require(block.timestamp < _at); // should be great than current block timestamp sT2 = _at; SetStartTimeTLP2(_at); } /** * @dev Large Token Holder minting * @param to - mint to address * @param amount - how much mint */ function fundMinting(address to, uint256 amount) stopInEmergency public { require(msg.sender == fundMintingAgent || isOwner()); require(block.timestamp < sT2); require(fundTotalSupply.add(amount) <= fundTokens); require(token.totalSupply().add(amount) <= hardCapInTokens); fundTotalSupply = fundTotalSupply.add(amount); token.mint(to, amount); FundMinting(to, amount); } /** * @dev calculate amount * @param amount - ether to be converted to tokens * @param at - current time * @param _totalSupply - total supplied tokens * @return tokens amount that we should send to our dear ppl * @return odd ethers amount, which contract should send back */ function calcAmountAt( uint256 amount, uint256 at, uint256 _totalSupply ) public constant returns (uint256, uint256) { uint256 estimate; uint256 price; if (at >= sT2 && at <= (sT2+dTLP2)) { if (at <= sT2 + 15 days) {price = 12e13;} else if (at <= sT2 + 30 days) { price = 14e13;} else if (at <= sT2 + 45 days) { price = 16e13;} else if (at <= sT2 + 60 days) { price = 18e13;} else if (at <= sT2 + 75 days) { price = 20e13;} else if (at <= sT2 + 90 days) { price = 22e13;} else if (at <= sT2 + 105 days) { price = 24e13;} else if (at <= sT2 + 118 days) { price = 26e13;} else {revert();} } else {revert();} estimate = _totalSupply.add(amount.mul(1e18).div(price)); if (estimate > hardCapInTokens) { return ( hardCapInTokens.sub(_totalSupply), estimate.sub(hardCapInTokens).mul(price).div(1e18) ); } return (estimate.sub(_totalSupply), 0); } /** * @dev fallback for processing ether */ function() external payable { return getTokens(msg.sender); } /** * @dev sell token and send to contributor address * @param contributor address */ function getTokens(address contributor) payable stopInEmergency validPurchase public { uint256 amount; uint256 oddEthers; uint256 ethers; uint256 _at; uint8 _winNum; _at = block.timestamp; require(contributor != 0x0); if (withinPeriod()) { (amount, oddEthers) = calcAmountAt(msg.value, _at, token.totalSupply()); require(amount.add(token.totalSupply()) <= hardCapInTokens); ethers = msg.value.sub(oddEthers); token.mint(contributor, amount); // fail if minting is finished TokenPurchase(contributor, ethers, amount); counter_in = counter_in.add(ethers); crowdTokensTLP2 = crowdTokensTLP2.add(amount); if (oddEthers > 0) { require(oddEthers < msg.value); contributor.transfer(oddEthers); TransferOddEther(contributor, oddEthers); } wallet.transfer(ethers); } else { require(msg.value >= minETHin); // checks min ETH income _winNum = stageName(); require(_winNum >= 0 && _winNum < 5); Window storage w = ww[_winNum]; require(w.tokenPerWindow > 0); // check that we have tokens! w.totalEthInWindow = w.totalEthInWindow.add(msg.value); ppls[w.totalTransCnt].addr = contributor; ppls[w.totalTransCnt].amount = msg.value; w.totalTransCnt++; TokenPurchaseInWindow(contributor, msg.value, _winNum, w.totalTransCnt, w.totalEthInWindow); } } /** * @dev close Window and transfer Eth to wallet address * @param _winNum - number of window 0-4 to close */ function closeWindow(uint8 _winNum) onlyOwner stopInEmergency public { require(ww[_winNum].active); ww[_winNum].active = false; wallet.transfer(this.balance); } /** * @dev transfer tokens to ppl accts (window1-5) * @param _winNum - number of window 0-4 to close */ function sendTokensWindow(uint8 _winNum) onlyOwner stopInEmergency public { uint256 _tokenPerETH; uint256 _tokenToSend = 0; address _tempAddr; uint32 index = ww[_winNum].refundIndex; TokenETH(ww[_winNum].totalEthInWindow, ww[_winNum].totalTransCnt); require(ww[_winNum].active); require(ww[_winNum].totalEthInWindow > 0); require(ww[_winNum].totalTransCnt > 0); _tokenPerETH = ww[_winNum].tokenPerWindow.div(ww[_winNum].totalEthInWindow); // max McFly in window / ethInWindow while (index < ww[_winNum].totalTransCnt && msg.gas > 100000) { _tokenToSend = _tokenPerETH.mul(ppls[index].amount); ppls[index].amount = 0; _tempAddr = ppls[index].addr; ppls[index].addr = 0; index++; token.transfer(_tempAddr, _tokenToSend); TokenWithdrawAtWindow(_tempAddr, _tokenToSend); } ww[_winNum].refundIndex = index; } /** * @dev open new window 0-5 and write totl token per window in structure * @param _winNum - number of window 0-4 to close * @param _tokenPerWindow - total token for window 0-4 */ function newWindow(uint8 _winNum, uint256 _tokenPerWindow) private { ww[_winNum] = Window(true, 0, 0, 0, _tokenPerWindow); NewWindow(_winNum, _tokenPerWindow); } /** * @dev Finish crowdsale TLP1.2 period and open window1-5 crowdsale */ function finishCrowd() onlyOwner public { uint256 _tokenPerWindow; require(now > (sT2.add(dTLP2)) || hardCapInTokens == token.totalSupply()); require(!token.mintingFinished()); _tokenPerWindow = (mintCapInTokens.sub(crowdTokensTLP2).sub(fundTotalSupply)).div(5); token.mint(this, _tokenPerWindow.mul(5)); // mint to contract address // shoud be MAX tokens minted!!! 1,800,000,000 for (uint8 y = 0; y < 5; y++) { newWindow(y, _tokenPerWindow); } token.finishMinting(); } /** * @dev withdraw tokens amount within vesting rules for team, advisory and reserved * @param withdrawWallet - wallet to transfer tokens * @param withdrawTokens - amount of tokens to transfer to * @param withdrawTotalSupply - total amount of tokens transfered to account * @return unit256 total amount of tokens after transfer */ function vestingWithdraw(address withdrawWallet, uint256 withdrawTokens, uint256 withdrawTotalSupply) private returns (uint256) { require(token.mintingFinished()); require(msg.sender == withdrawWallet || isOwner()); uint256 currentPeriod = (block.timestamp.sub(sT2.add(dTLP2))).div(VestingPeriodInSeconds); if (currentPeriod > VestingPeriodsCount) { currentPeriod = VestingPeriodsCount; } uint256 tokenAvailable = withdrawTokens.mul(currentPeriod).div(VestingPeriodsCount).sub(withdrawTotalSupply); // RECHECK!!!!! require((withdrawTotalSupply.add(tokenAvailable)) <= withdrawTokens); uint256 _withdrawTotalSupply = withdrawTotalSupply.add(tokenAvailable); token.transfer(withdrawWallet, tokenAvailable); WithdrawVesting(withdrawWallet, currentPeriod, tokenAvailable, _withdrawTotalSupply); return _withdrawTotalSupply; } /** * @dev withdraw tokens amount within vesting rules for team */ function teamWithdraw() public { teamTotalSupply = vestingWithdraw(teamWallet, _teamTokens, teamTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for advisory */ function advisoryWithdraw() public { advisoryTotalSupply = vestingWithdraw(advisoryWallet, _advisoryTokens, advisoryTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for reserved wallet */ function reservedWithdraw() public { reservedTotalSupply = vestingWithdraw(reservedWallet, _reservedTokens, reservedTotalSupply); } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; }
6,201,456
//Address: 0xcdf35c3fe4ccfacb3b1bbedfe71ca3a5ff6f2db1 //Contract name: GenericCrowdsale //Balance: 0 Ether //Verification Date: 3/18/2018 //Transacion Count: 12 // CODE STARTS HERE pragma solidity ^0.4.18; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); 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; } } contract ERC223 { uint public totalSupply; function balanceOf(address who) public view returns (uint); function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); function totalSupply() public view returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); } contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } contract StandardToken is ERC223 { using SafeMath for uint; //user token balances mapping (address => uint) balances; //token transer permissions mapping (address => mapping (address => uint)) allowed; // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { if(isContract(_to)) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); Transfer(msg.sender, _to, _value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balanceOf(msg.sender).sub(_value); balances[_to] = balanceOf(_to).add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); return true; } /** * Token transfer from from to _to (permission needed) */ function transferFrom( address _from, address _to, uint _value ) public returns (bool) { if (balanceOf(_from) < _value && allowance(_from, msg.sender) < _value) revert(); bytes memory empty; balances[_to] = balanceOf(_to).add(_value); balances[_from] = balanceOf(_from).sub(_value); allowed[_from][msg.sender] = allowance(_from, msg.sender).sub(_value); if (isContract(_to)) { ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(_from, _to, _value); return true; } /** * Increase permission for transfer */ function increaseApproval( address spender, uint value ) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(value); return true; } /** * Decrease permission for transfer */ function decreaseApproval( address spender, uint value ) public returns (bool) { allowed[msg.sender][spender] = allowed[msg.sender][spender].add(value); return true; } /** * User token balance */ function balanceOf( address owner ) public constant returns (uint) { return balances[owner]; } /** * User transfer permission */ function allowance( address owner, address spender ) public constant returns (uint remaining) { return allowed[owner][spender]; } } contract MyDFSToken is StandardToken { string public name = "MyDFS Token"; uint8 public decimals = 6; string public symbol = "MyDFS"; string public version = 'H1.0'; uint256 public totalSupply; function () external { revert(); } function MyDFSToken() public { totalSupply = 125 * 1e12; balances[msg.sender] = totalSupply; } // Function to access name of token . function name() public view returns (string _name) { return name; } // Function to access symbol of token . function symbol() public view returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() public view returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } } contract Ownable { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed _by, address indexed _to); event OwnershipTransferred(address indexed _from, address indexed _to); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _;} /// Proposes to transfer control of the contract to a newOwnerCandidate. /// @param _newOwnerCandidate address The address to transfer ownership to. function transferOwnership(address _newOwnerCandidate) external onlyOwner { require(_newOwnerCandidate != address(0)); newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } /// Accept ownership transfer. This method needs to be called by the perviously proposed owner. function acceptOwnership() external { if (msg.sender == newOwnerCandidate) { owner = newOwnerCandidate; newOwnerCandidate = address(0); OwnershipTransferred(owner, newOwnerCandidate); } } } contract DevTokensHolder is Ownable { using SafeMath for uint256; uint256 collectedTokens; GenericCrowdsale crowdsale; MyDFSToken token; event ClaimedTokens(address token, uint256 amount); event TokensWithdrawn(address holder, uint256 amount); event Debug(uint256 amount); function DevTokensHolder(address _crowdsale, address _token, address _owner) public { crowdsale = GenericCrowdsale(_crowdsale); token = MyDFSToken(_token); owner = _owner; } function tokenFallback( address _from, uint _value, bytes _data ) public view { require(_from == owner || _from == address(crowdsale)); require(_value > 0 || _data.length > 0); } /// @notice The Dev (Owner) will call this method to extract the tokens function collectTokens() public onlyOwner { uint256 balance = token.balanceOf(address(this)); uint256 total = collectedTokens.add(balance); uint256 finalizedTime = crowdsale.finishTime(); require(finalizedTime > 0 && getTime() > finalizedTime.add(14 days)); uint256 canExtract = total.mul(getTime().sub(finalizedTime)).div(months(12)); canExtract = canExtract.sub(collectedTokens); if (canExtract > balance) { canExtract = balance; } collectedTokens = collectedTokens.add(canExtract); require(token.transfer(owner, canExtract)); TokensWithdrawn(owner, canExtract); } function months(uint256 m) internal pure returns (uint256) { return m.mul(30 days); } function getTime() internal view returns (uint256) { return now; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { require(_token != address(token)); if (_token == 0x0) { owner.transfer(this.balance); return; } token = MyDFSToken(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, balance); } } contract AdvisorsTokensHolder is Ownable { using SafeMath for uint256; GenericCrowdsale crowdsale; MyDFSToken token; event ClaimedTokens(address token, uint256 amount); event TokensWithdrawn(address holder, uint256 amount); function AdvisorsTokensHolder(address _crowdsale, address _token, address _owner) public { crowdsale = GenericCrowdsale(_crowdsale); token = MyDFSToken(_token); owner = _owner; } function tokenFallback( address _from, uint _value, bytes _data ) public view { require(_from == owner || _from == address(crowdsale)); require(_value > 0 || _data.length > 0); } /// @notice The Dev (Owner) will call this method to extract the tokens function collectTokens() public onlyOwner { uint256 balance = token.balanceOf(address(this)); require(balance > 0); uint256 finalizedTime = crowdsale.finishTime(); require(finalizedTime > 0 && getTime() > finalizedTime.add(14 days)); require(token.transfer(owner, balance)); TokensWithdrawn(owner, balance); } function getTime() internal view returns (uint256) { return now; } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) public onlyOwner { require(_token != address(token)); if (_token == 0x0) { owner.transfer(this.balance); return; } token = MyDFSToken(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); ClaimedTokens(_token, balance); } } contract GenericCrowdsale is Ownable { using SafeMath for uint256; //Crowrdsale states enum State { Initialized, PreIco, PreIcoFinished, Ico, IcoFinished} struct Discount { uint256 amount; uint256 value; } //ether trasfered to address public beneficiary; //Crowrdsale state State public state; //Hard goal in Wei uint public hardFundingGoal; //soft goal in Wei uint public softFundingGoal; //gathered Ether amount in Wei uint public amountRaised; //ICO/PreICO start timestamp in seconds uint public started; //Crowdsale finish time uint public finishTime; //price for 1 token in Wei uint public price; //minimum purchase value in Wei uint public minPurchase; //Token cantract ERC223 public tokenReward; //Wei balances for refund if ICO failed mapping(address => uint256) public balances; //Emergency stop sell bool emergencyPaused = false; //Soft cap reached bool softCapReached = false; //dev holder DevTokensHolder public devTokensHolder; //advisors holder AdvisorsTokensHolder public advisorsTokensHolder; //Disconts Discount[] public discounts; //price overhead for next stages uint8[2] public preIcoTokenPrice = [70,75]; //price overhead for next stages uint8[4] public icoTokenPrice = [100,120,125,130]; event TokenPurchased(address investor, uint sum, uint tokensCount, uint discountTokens); event PreIcoLimitReached(uint totalAmountRaised); event SoftGoalReached(uint totalAmountRaised); event HardGoalReached(uint totalAmountRaised); event Debug(uint num); //Sale is active modifier sellActive() { require( !emergencyPaused && (state == State.PreIco || state == State.Ico) && amountRaised < hardFundingGoal ); _; } //Soft cap not reached modifier goalNotReached() { require(state == State.IcoFinished && amountRaised < softFundingGoal); _; } /** * Constrctor function */ function GenericCrowdsale( address ifSuccessfulSendTo, address addressOfTokenUsedAsReward ) public { require(ifSuccessfulSendTo != address(0) && addressOfTokenUsedAsReward != address(0)); beneficiary = ifSuccessfulSendTo; tokenReward = ERC223(addressOfTokenUsedAsReward); state = State.Initialized; } function tokenFallback( address _from, uint _value, bytes _data ) public view { require(_from == owner); require(_value > 0 || _data.length > 0); } /** * Start PreICO */ function preIco( uint hardFundingGoalInEthers, uint minPurchaseInFinney, uint costOfEachToken, uint256[] discountEthers, uint256[] discountValues ) external onlyOwner { require(hardFundingGoalInEthers > 0 && costOfEachToken > 0 && state == State.Initialized && discountEthers.length == discountValues.length); hardFundingGoal = hardFundingGoalInEthers.mul(1 ether); minPurchase = minPurchaseInFinney.mul(1 finney); price = costOfEachToken; initDiscounts(discountEthers, discountValues); state = State.PreIco; started = now; } /** * Start ICO */ function ico( uint softFundingGoalInEthers, uint hardFundingGoalInEthers, uint minPurchaseInFinney, uint costOfEachToken, uint256[] discountEthers, uint256[] discountValues ) external onlyOwner { require(softFundingGoalInEthers > 0 && hardFundingGoalInEthers > 0 && hardFundingGoalInEthers > softFundingGoalInEthers && costOfEachToken > 0 && state < State.Ico && discountEthers.length == discountValues.length); softFundingGoal = softFundingGoalInEthers.mul(1 ether); hardFundingGoal = hardFundingGoalInEthers.mul(1 ether); minPurchase = minPurchaseInFinney.mul(1 finney); price = costOfEachToken; delete discounts; initDiscounts(discountEthers, discountValues); state = State.Ico; started = now; } /** * Finish ICO / PreICO */ function finishSale() external onlyOwner { require(state == State.PreIco || state == State.Ico); if (state == State.PreIco) state = State.PreIcoFinished; else state = State.IcoFinished; } /** * Admin can pause token sell */ function emergencyPause() external onlyOwner { emergencyPaused = true; } /** * Admin can unpause token sell */ function emergencyUnpause() external onlyOwner { emergencyPaused = false; } /** * Transfer dev tokens to vesting wallet */ function sendDevTokens() external onlyOwner returns(address) { require(successed()); devTokensHolder = new DevTokensHolder(address(this), address(tokenReward), owner); tokenReward.transfer(address(devTokensHolder), 12500 * 1e9); return address(devTokensHolder); } /** * Transfer dev tokens to vesting wallet */ function sendAdvisorsTokens() external onlyOwner returns(address) { require(successed()); advisorsTokensHolder = new AdvisorsTokensHolder(address(this), address(tokenReward), owner); tokenReward.transfer(address(advisorsTokensHolder), 12500 * 1e9); return address(advisorsTokensHolder); } /** * Admin can withdraw ether beneficiary address */ function withdrawFunding() external onlyOwner { require((state == State.PreIco || successed())); beneficiary.transfer(this.balance); } /** * Different coins purchase */ function foreignPurchase(address user, uint256 amount) external onlyOwner sellActive { buyTokens(user, amount); checkGoals(); } /** * Claim refund ether in soft goal not reached */ function claimRefund() external goalNotReached { uint256 amount = balances[msg.sender]; balances[msg.sender] = 0; if (amount > 0){ if (!msg.sender.send(amount)) { balances[msg.sender] = amount; } } } /** * Payment transaction */ function () external payable sellActive { require(msg.value > 0); require(msg.value >= minPurchase); uint amount = msg.value; if (amount > hardFundingGoal.sub(amountRaised)) { uint availableAmount = hardFundingGoal.sub(amountRaised); msg.sender.transfer(amount.sub(availableAmount)); amount = availableAmount; } buyTokens(msg.sender, amount); checkGoals(); } /** * Transfer tokens to user */ function buyTokens( address user, uint256 amount ) internal { require(amount <= hardFundingGoal.sub(amountRaised)); uint256 passedSeconds = getTime().sub(started); uint256 week = 0; if (passedSeconds >= 604800){ week = passedSeconds.div(604800); } Debug(week); uint256 tokenPrice; if (state == State.Ico){ uint256 cup = amountRaised.mul(4).div(hardFundingGoal); if (cup > week) week = cup; if (week >= 4) week = 3; tokenPrice = price.mul(icoTokenPrice[week]).div(100); } else { if (week >= 2) week = 1; tokenPrice = price.mul(preIcoTokenPrice[week]).div(100); } Debug(tokenPrice); uint256 count = amount.div(tokenPrice); uint256 discount = getDiscountOf(amount); uint256 discountBonus = discount.mul(count).div(100); count = count.add(discountBonus); count = ceilTokens(count); require(tokenReward.transfer(user, count)); balances[user] = balances[user].add(amount); amountRaised = amountRaised.add(amount); TokenPurchased(user, amount, count, discountBonus); } /** * Define distount percents for different token amounts */ function ceilTokens( uint256 num ) public pure returns(uint256) { uint256 part = num % 1000000; return part > 0 ? num.div(1000000).mul(1000000) + 1000000 : num; } /** * ICO is finished successfully */ function successed() public view returns(bool) { return state == State.IcoFinished && amountRaised >= softFundingGoal; } /** * Define distount percents for different token amounts */ function initDiscounts( uint256[] discountEthers, uint256[] discountValues ) internal { for (uint256 i = 0; i < discountEthers.length; i++) { discounts.push(Discount(discountEthers[i].mul(1 ether), discountValues[i])); } } /** * Get discount percent for number of tokens */ function getDiscountOf( uint256 _amount ) public view returns (uint256) { if (discounts.length > 0) for (uint256 i = 0; i < discounts.length; i++) { if (_amount >= discounts[i].amount) { return discounts[i].value; } } return 0; } /** * Check ICO goals achievement */ function checkGoals() internal { if (state == State.PreIco) { if (amountRaised >= hardFundingGoal) { PreIcoLimitReached(amountRaised); state = State.PreIcoFinished; } } else { if (!softCapReached && amountRaised >= softFundingGoal){ softCapReached = true; SoftGoalReached(amountRaised); } if (amountRaised >= hardFundingGoal) { finishTime = now; HardGoalReached(amountRaised); state = State.IcoFinished; } } } function getTime() internal view returns (uint) { return now; } }
Define distount percents for different token amounts/
function ceilTokens( uint256 num ) public pure returns(uint256) { uint256 part = num % 1000000; return part > 0 ? num.div(1000000).mul(1000000) + 1000000 : num; }
2,505,408
/*** * ██████╗ ███████╗ ██████╗ ██████╗ * ██╔══██╗██╔════╝██╔════╝ ██╔═══██╗ * ██║ ██║█████╗ ██║ ███╗██║ ██║ * ██║ ██║██╔══╝ ██║ ██║██║ ██║ * ██████╔╝███████╗╚██████╔╝╚██████╔╝ * ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ * * https://dego.finance * MIT License * =========== * * Copyright (c) 2020 dego * * 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 */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol 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; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * 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; } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.5.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.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; 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 safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/drafts/Counters.sol pragma solidity ^0.5.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // File: @openzeppelin/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.5.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, 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. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @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) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } // File: @openzeppelin/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity ^0.5.0; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } // File: contracts/interface/IERC20.sol 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); function mint(address account, uint amount) external; /** * @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/library/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/library/Governance.sol pragma solidity ^0.5.0; contract Governance { address public _governance; constructor() public { _governance = tx.origin; } event GovernanceTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyGovernance { require(msg.sender == _governance, "not governance"); _; } function setGovernance(address governance) public onlyGovernance { require(governance != address(0), "new governance the zero address"); emit GovernanceTransferred(_governance, governance); _governance = governance; } } // File: contracts/interface/IPool.sol pragma solidity ^0.5.0; interface IPool { function totalSupply( ) external view returns (uint256); function balanceOf( address player ) external view returns (uint256); } // File: contracts/interface/IPlayerBook.sol pragma solidity ^0.5.0; interface IPlayerBook { function settleReward( address from,uint256 amount ) external returns (uint256); function bindRefer( address from,string calldata affCode ) external returns (bool); function hasRefer(address from) external returns(bool); } // File: contracts/interface/IGegoFactory.sol pragma solidity ^0.5.0; interface IGegoFactory { function getGego(uint256 tokenId) external view returns ( uint256 grade, uint256 quality, uint256 degoAmount, uint256 createdTime, uint256 blockNum, uint256 resId, address author ); function getQualityBase() external view returns (uint256 ); } // File: contracts/interface/IGegoToken.sol pragma solidity ^0.5.0; contract IGegoToken is IERC721 { function mint(address to, uint256 tokenId) external returns (bool) ; function burn(uint256 tokenId) external; } // File: contracts/reward/NFTReward.sol pragma solidity ^0.5.0; // gego // import "../interface/IERC20.sol"; contract NFTReward is IPool,Governance { using SafeERC20 for IERC20; using SafeMath for uint256; IERC20 public _dego = IERC20(0x0); IGegoFactory public _gegoFactory = IGegoFactory(0x0); IGegoToken public _gegoToken = IGegoToken(0x0); address public _playerBook = address(0x0); address public _teamWallet = 0x3D0a845C5ef9741De999FC068f70E2048A489F2b; address public _rewardPool = 0xEA6dEc98e137a87F78495a8386f7A137408f7722; uint256 public constant DURATION = 7 days; uint256 public _initReward = 52500 * 1e18; uint256 public _startTime = now + 365 days; uint256 public _periodFinish = 0; uint256 public _rewardRate = 0; uint256 public _lastUpdateTime; uint256 public _rewardPerTokenStored; uint256 public _teamRewardRate = 500; uint256 public _poolRewardRate = 1000; uint256 public _baseRate = 10000; uint256 public _punishTime = 3 days; mapping(address => uint256) public _userRewardPerTokenPaid; mapping(address => uint256) public _rewards; mapping(address => uint256) public _lastStakedTime; bool public _hasStart = false; uint256 public _fixRateBase = 100000; uint256 public _totalWeight; mapping(address => uint256) public _weightBalances; mapping(uint256 => uint256) public _stakeWeightes; mapping(uint256 => uint256) public _stakeBalances; uint256 public _totalBalance; mapping(address => uint256) public _degoBalances; uint256 public _maxStakedDego = 200 * 1e18; mapping(address => uint256[]) public _playerGego; mapping(uint256 => uint256) public _gegoMapIndex; event RewardAdded(uint256 reward); event StakedGEGO(address indexed user, uint256 amount); event WithdrawnGego(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event NFTReceived(address operator, address from, uint256 tokenId, bytes data); constructor(address dego, address gego, address gegoFactory,address playerBook) public { _dego = IERC20(dego); _gegoToken = IGegoToken(gego); _gegoFactory = IGegoFactory(gegoFactory); _playerBook = playerBook; } modifier updateReward(address account) { _rewardPerTokenStored = rewardPerToken(); _lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { _rewards[account] = earned(account); _userRewardPerTokenPaid[account] = _rewardPerTokenStored; } _; } function setMaxStakedDego(uint256 amount) external onlyGovernance{ _maxStakedDego = amount; } /* Fee collection for any other token */ function seize(IERC20 token, uint256 amount) external onlyGovernance{ require(token != _dego, "reward"); token.safeTransfer(_governance, amount); } /* Fee collection for any other token */ function seizeErc721(IERC721 token, uint256 tokenId) external { require(token != _gegoToken, "gego stake"); token.safeTransferFrom(address(this), _governance, tokenId); } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, _periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return _rewardPerTokenStored; } return _rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(_lastUpdateTime) .mul(_rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(_userRewardPerTokenPaid[account])) .div(1e18) .add(_rewards[account]); } //the grade is a number between 1-6 //the quality is a number between 1-10000 /* 1 quality 1.1+ 0.1*quality/5000 2 quality 1.2+ 0.1*(quality-5000)/3000 3 quality 1.3+ 0.1*(quality-8000/1000 4 quality 1.4+ 0.2*(quality-9000)/800 5 quality 1.6+ 0.2*(quality-9800)/180 6 quality 1.8+ 0.2*(quality-9980)/20 */ function getFixRate(uint256 grade,uint256 quality) public pure returns (uint256){ require(grade > 0 && grade <7, "the gego not dego"); uint256 unfold = 0; if( grade == 1 ){ unfold = quality*10000/5000; return unfold.add(110000); }else if( grade == 2){ unfold = quality.sub(5000)*10000/3000; return unfold.add(120000); }else if( grade == 3){ unfold = quality.sub(8000)*10000/1000; return unfold.add(130000); }else if( grade == 4){ unfold = quality.sub(9000)*20000/800; return unfold.add(140000); }else if( grade == 5){ unfold = quality.sub(9800)*20000/180; return unfold.add(160000); }else{ unfold = quality.sub(9980)*20000/20; return unfold.add(180000); } } function getStakeInfo( uint256 gegoId ) public view returns ( uint256 stakeRate, uint256 degoAmount){ uint256 grade; uint256 quality; uint256 createdTime; uint256 blockNum; uint256 resId; address author; (grade, quality, degoAmount, createdTime,blockNum, resId, author) = _gegoFactory.getGego(gegoId); require(degoAmount > 0,"the gego not dego"); stakeRate = getFixRate(grade,quality); } // stake GEGO function stakeGego(uint256 gegoId, string memory affCode) public updateReward(msg.sender) checkHalve checkStart { uint256[] storage gegoIds = _playerGego[msg.sender]; if (gegoIds.length == 0) { gegoIds.push(0); _gegoMapIndex[0] = 0; } gegoIds.push(gegoId); _gegoMapIndex[gegoId] = gegoIds.length - 1; uint256 stakeRate; uint256 degoAmount; (stakeRate, degoAmount) = getStakeInfo(gegoId); uint256 stakedDegoAmount = _degoBalances[msg.sender]; uint256 stakingDegoAmount = stakedDegoAmount.add(degoAmount) <= _maxStakedDego?degoAmount:_maxStakedDego.sub(stakedDegoAmount); if(stakingDegoAmount > 0){ uint256 stakeWeight = stakeRate.mul(stakingDegoAmount).div(_fixRateBase); _degoBalances[msg.sender] = _degoBalances[msg.sender].add(stakingDegoAmount); _weightBalances[msg.sender] = _weightBalances[msg.sender].add(stakeWeight); _stakeBalances[gegoId] = stakingDegoAmount; _stakeWeightes[gegoId] = stakeWeight; _totalBalance = _totalBalance.add(stakingDegoAmount); _totalWeight = _totalWeight.add(stakeWeight); } _gegoToken.safeTransferFrom(msg.sender, address(this), gegoId); if (!IPlayerBook(_playerBook).hasRefer(msg.sender)) { IPlayerBook(_playerBook).bindRefer(msg.sender, affCode); } _lastStakedTime[msg.sender] = now; emit StakedGEGO(msg.sender, gegoId); } function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4) { if(_hasStart == false) { return 0; } emit NFTReceived(operator, from, tokenId, data); return bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); } function withdrawGego(uint256 gegoId) public updateReward(msg.sender) checkHalve checkStart { require(gegoId > 0, "the gegoId error"); uint256[] memory gegoIds = _playerGego[msg.sender]; uint256 gegoIndex = _gegoMapIndex[gegoId]; require(gegoIds[gegoIndex] == gegoId, "not gegoId owner"); uint256 gegoArrayLength = gegoIds.length-1; uint256 tailId = gegoIds[gegoArrayLength]; _playerGego[msg.sender][gegoIndex] = tailId; _playerGego[msg.sender][gegoArrayLength] = 0; _playerGego[msg.sender].length--; _gegoMapIndex[tailId] = gegoIndex; _gegoMapIndex[gegoId] = 0; uint256 stakeWeight = _stakeWeightes[gegoId]; _weightBalances[msg.sender] = _weightBalances[msg.sender].sub(stakeWeight); _totalWeight = _totalWeight.sub(stakeWeight); uint256 stakeBalance = _stakeBalances[gegoId]; _degoBalances[msg.sender] = _degoBalances[msg.sender].sub(stakeBalance); _totalBalance = _totalBalance.sub(stakeBalance); _gegoToken.safeTransferFrom(address(this), msg.sender, gegoId); _stakeBalances[gegoId] = 0; _stakeWeightes[gegoId] = 0; emit WithdrawnGego(msg.sender, gegoId); } function withdraw() public checkStart { uint256[] memory gegoId = _playerGego[msg.sender]; for (uint8 index = 1; index < gegoId.length; index++) { if (gegoId[index] > 0) { withdrawGego(gegoId[index]); } } } function getPlayerIds( address account ) public view returns( uint256[] memory gegoId ) { gegoId = _playerGego[account]; } function exit() external { withdraw(); getReward(); } function getReward() public updateReward(msg.sender) checkHalve checkStart { uint256 reward = earned(msg.sender); if (reward > 0) { _rewards[msg.sender] = 0; uint256 fee = IPlayerBook(_playerBook).settleReward(msg.sender, reward); if(fee > 0){ _dego.safeTransfer(_playerBook, fee); } uint256 teamReward = reward.mul(_teamRewardRate).div(_baseRate); if(teamReward>0){ _dego.safeTransfer(_teamWallet, teamReward); } uint256 leftReward = reward.sub(fee).sub(teamReward); uint256 poolReward = 0; //withdraw time check if(now < (_lastStakedTime[msg.sender] + _punishTime) ){ poolReward = leftReward.mul(_poolRewardRate).div(_baseRate); } if(poolReward>0){ _dego.safeTransfer(_rewardPool, poolReward); leftReward = leftReward.sub(poolReward); } if(leftReward>0){ _dego.safeTransfer(msg.sender, leftReward ); } emit RewardPaid(msg.sender, leftReward); } } modifier checkHalve() { if (block.timestamp >= _periodFinish) { _initReward = _initReward.mul(50).div(100); _dego.mint(address(this), _initReward); _rewardRate = _initReward.div(DURATION); _periodFinish = block.timestamp.add(DURATION); emit RewardAdded(_initReward); } _; } modifier checkStart() { require(block.timestamp > _startTime, "not start"); _; } // set fix time to start reward function startNFTReward(uint256 startTime) external onlyGovernance updateReward(address(0)) { require(_hasStart == false, "has started"); _hasStart = true; _startTime = startTime; _rewardRate = _initReward.div(DURATION); _dego.mint(address(this), _initReward); _lastUpdateTime = _startTime; _periodFinish = _startTime.add(DURATION); emit RewardAdded(_initReward); } // //for extra reward function notifyMintAmount(uint256 reward) external onlyGovernance updateReward(address(0)) { // IERC20(_dego).safeTransferFrom(msg.sender, address(this), reward); _dego.mint(address(this), reward); if (block.timestamp >= _periodFinish) { _rewardRate = reward.div(DURATION); } else { uint256 remaining = _periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(_rewardRate); _rewardRate = reward.add(leftover).div(DURATION); } _lastUpdateTime = block.timestamp; _periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } function setTeamRewardRate( uint256 teamRewardRate ) public onlyGovernance { _teamRewardRate = teamRewardRate; } function setPoolRewardRate( uint256 poolRewardRate ) public onlyGovernance{ _poolRewardRate = poolRewardRate; } function totalSupply() public view returns (uint256) { return _totalWeight; } function balanceOf(address account) public view returns (uint256) { return _weightBalances[account]; } function setWithDrawPunishTime( uint256 punishTime ) public onlyGovernance{ _punishTime = punishTime; } }
Fee collection for any other token /
function seize(IERC20 token, uint256 amount) external onlyGovernance{ require(token != _dego, "reward"); token.safeTransfer(_governance, amount); }
5,816,751
// SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; /* BEGIN KEYBASE SALTPACK SIGNED MESSAGE. kXR7VktZdyH7rvq v5weRa0zkYfegFM 5cM6gB7cyPatQvp 6KyygX8PsvQVo4n Ugo6Il5bm5f3Wc6 6TBmPpX0GwuU4n1 jj5f1QNCcPGgXgB 2CnpFgQ3gOEvVg6 XP8CXBnyC9E1gRc gI54di8USKNHywe 5kNeA6zdEcwdKsZ 3Ydod13RrV78Qap G7mca59khDyl2mo iCT5TurbhMcXtFI Z3kVTS4fqbGrGvT RN6eTFmOIlmGzsu 7UUxkeBmUQ5LV5k 9V0AHCX5ZLAjz5f y2Q. END KEYBASE SALTPACK SIGNED MESSAGE. */ import './libraries/ViralswapLibrary.sol'; import './libraries/SafeMath.sol'; import './libraries/TransferHelper.sol'; import './interfaces/IViralswapRouter02.sol'; import './interfaces/IUniswapRouter02.sol'; import './interfaces/IViralswapFactory.sol'; import './interfaces/IERC20.sol'; import './interfaces/IWETH.sol'; contract ViralswapRouter02 is IViralswapRouter02 { using SafeMathViralswap for uint; address public immutable override factory; address public immutable override WETH; address public immutable override VIRAL; address public immutable override altRouter; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'ViralswapRouter: EXPIRED'); _; } constructor(address _factory, address _WETH, address _VIRAL, address _altRouter) public { factory = _factory; WETH = _WETH; VIRAL = _VIRAL; altRouter = _altRouter; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin ) internal virtual returns (uint amountA, uint amountB) { // create the pair if it doesn't exist yet if (IViralswapFactory(factory).getPair(tokenA, tokenB) == address(0)) { IViralswapFactory(factory).createPair(tokenA, tokenB); } (uint reserveA, uint reserveB) = ViralswapLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint amountBOptimal = ViralswapLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require(amountBOptimal >= amountBMin, 'ViralswapRouter: INSUFFICIENT_B_AMOUNT'); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint amountAOptimal = ViralswapLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require(amountAOptimal >= amountAMin, 'ViralswapRouter: INSUFFICIENT_A_AMOUNT'); (amountA, amountB) = (amountAOptimal, amountBDesired); } } } function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); address pair = ViralswapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IViralswapPair(pair).mint(to); } function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = ViralswapLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IViralswapPair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { address pair = ViralswapLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(pair, msg.sender, pair, liquidity); // send liquidity to pair (uint amount0, uint amount1) = IViralswapPair(pair).burn(to); (address token0,) = ViralswapLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, 'ViralswapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= amountBMin, 'ViralswapRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { (amountToken, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountA, uint amountB) { address pair = ViralswapLibrary.pairFor(factory, tokenA, tokenB); uint value = approveMax ? uint(-1) : liquidity; IViralswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountToken, uint amountETH) { address pair = ViralswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IViralswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); } // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { (, amountETH) = removeLiquidity( token, WETH, liquidity, amountTokenMin, amountETHMin, address(this), deadline ); TransferHelper.safeTransfer(token, to, IERC20Viralswap(token).balanceOf(address(this))); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external virtual override returns (uint amountETH) { address pair = ViralswapLibrary.pairFor(factory, token, WETH); uint value = approveMax ? uint(-1) : liquidity; IViralswapPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( token, liquidity, amountTokenMin, amountETHMin, to, deadline ); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(false, "ViralswapRouter02: Not implemented"); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual returns(uint256 finalAmountOutput) { for (uint i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0,) = ViralswapLibrary.sortTokens(input, output); IViralswapPair pair = IViralswapPair(ViralswapLibrary.pairFor(factory, input, output)); uint amountInput; uint amountOutput; { // scope to avoid stack too deep errors (uint reserve0, uint reserve1,) = pair.getReserves(); (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IERC20Viralswap(input).balanceOf(address(pair)).sub(reserveInput); amountOutput = ViralswapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); } (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); address to = i < path.length - 2 ? ViralswapLibrary.pairFor(factory, output, path[i + 2]) : _to; pair.swap(amount0Out, amount1Out, to, new bytes(0)); finalAmountOutput = amountOutput; } } /** * @dev Function to swap an exact amount of VIRAL for other tokens * Leverages the `altRouter` for swaps not concerning VIRAL * * @param amountIn : the input amount of VIRAL to swap * @param amountOutMin : the minimum output amount for tokenOut * @param path : [USDC, ..., tokenOut] * @param to : the address to receive tokenOut * @param deadline : timestamp by which the transaction must complete **/ function swapExactViralForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( VIRAL, msg.sender, ViralswapLibrary.pairFor(factory, VIRAL, path[0]), amountIn ); uint256 balanceBefore = IERC20Viralswap(path[path.length - 1]).balanceOf(to); address[] memory fullPath = new address[](2); fullPath[0] = VIRAL; fullPath[1] = path[0]; if(path.length == 1) { _swapSupportingFeeOnTransferTokens(fullPath, to); } else { uint256 finalAmountOutput = _swapSupportingFeeOnTransferTokens(fullPath, address(this)); IERC20Viralswap(path[0]).approve(altRouter, finalAmountOutput); IUniswapV2Router02(altRouter).swapExactTokensForTokensSupportingFeeOnTransferTokens( finalAmountOutput, amountOutMin, path, to, deadline ); } require( IERC20Viralswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @dev Function to swap an exact amount of VIRAL for ETH * Leverages the `altRouter` for swaps not concerning VIRAL * * @param amountIn : the input amount of VIRAL to swap * @param amountOutMin : the minimum output amount for ETH * @param path : [USDC, ..., WETH] * @param to : the address to receive ETH * @param deadline : timestamp by which the transaction must complete **/ function swapExactViralForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( VIRAL, msg.sender, ViralswapLibrary.pairFor(factory, VIRAL, path[0]), amountIn ); uint256 balanceBefore = to.balance; address[] memory fullPath = new address[](2); fullPath[0] = VIRAL; fullPath[1] = path[0]; uint256 finalAmountOutput = _swapSupportingFeeOnTransferTokens(fullPath, address(this)); IERC20Viralswap(path[0]).approve(altRouter, finalAmountOutput); IUniswapV2Router02(altRouter).swapExactTokensForETHSupportingFeeOnTransferTokens( finalAmountOutput, amountOutMin, path, to, deadline ); require( to.balance.sub(balanceBefore) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @dev Function to swap an exact amount of token for VIRAL * Leverages the `altRouter` for swaps not concerning VIRAL * * @param amountIn : the input amount of tokenIn * @param amountOutMin : the minimum output amount for VIRAL * @param path : [tokenIn, ..., USDC] * @param to : the address to receive VIRAL * @param deadline : timestamp by which the transaction must complete **/ function swapExactTokensForViralSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { if(path.length == 1) { TransferHelper.safeTransferFrom( path[0], msg.sender, ViralswapLibrary.pairFor(factory, path[0], VIRAL), amountIn ); } else { TransferHelper.safeTransferFrom( path[0], msg.sender, address(this), amountIn ); address lastToken = path[path.length - 1]; IERC20Viralswap(path[0]).approve(altRouter, amountIn); IUniswapV2Router02(altRouter).swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn, 0, path, ViralswapLibrary.pairFor(factory, VIRAL, lastToken), deadline ); } uint256 balanceBefore = IERC20Viralswap(VIRAL).balanceOf(to); address[] memory fullPath = new address[](2); fullPath[0] = path[path.length - 1]; fullPath[1] = VIRAL; _swapSupportingFeeOnTransferTokens(fullPath, to); require( IERC20Viralswap(VIRAL).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, ViralswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20Viralswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Viralswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'ViralswapRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(ViralswapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20Viralswap(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IERC20Viralswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'ViralswapRouter: INVALID_PATH'); TransferHelper.safeTransferFrom( path[0], msg.sender, ViralswapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint amountOut = IERC20Viralswap(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** BUY **** // requires the initial amount to have already been sent to the vault function _buy(uint[] memory amounts, address[] memory path, address _to) internal virtual { require(path.length == 2, 'ViralswapRouter: INVALID_PATH_LENGTH'); (address input, address output) = (path[0], path[1]); IViralswapVault vault = IViralswapVault(ViralswapLibrary.vaultFor(factory, input, output)); require(input == vault.tokenIn() && output == vault.tokenOut(), 'ViralswapRouter: INCORRECT_PAIR'); vault.buy(amounts[1], _to); } /** * @dev Function to buy an exact number of tokens from the VIRAL Vault for the specified tokens. * * @param amountIn : the input amount for tokenIn * @param amountOutMin : the minimum output amount for tokenOut (is deterministic since the Vault is a fixed price instrument) * @param path : [tokenIn, tokenOut] * @param to : the address to receive tokenOut * @param deadline : timestamp by which the transaction must complete **/ function buyTokensForExactTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { amounts = new uint[](path.length); amounts[0] = amountIn; amounts[1] = ViralswapLibrary.getVaultAmountOut(factory, path[0], path[1], amountIn); require(amounts[1] >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom( path[0], msg.sender, ViralswapLibrary.vaultFor(factory, path[0], path[1]), amounts[0] ); _buy(amounts, path, to); } /** * @dev Function to buy VIRAL (using the Vault) from an exact amount of token * Leverages the `altRouter` for swaps not concerning VIRAL * * @param amountIn : the input amount of tokenIn * @param amountOutMin : the minimum output amount for VIRAL * @param path : [tokenIn, ..., USDC] * @param to : the address to receive VIRAL * @param deadline : timestamp by which the transaction must complete **/ function buyViralForExactTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { uint256 balanceBeforeIn; address lastToken = path[path.length - 1]; address vault; if(path.length == 1) { vault = ViralswapLibrary.vaultFor(factory, lastToken, VIRAL); balanceBeforeIn = IERC20Viralswap(lastToken).balanceOf(vault); TransferHelper.safeTransferFrom( lastToken, msg.sender, vault, amountIn ); } else { vault = ViralswapLibrary.vaultFor(factory, VIRAL, lastToken); balanceBeforeIn = IERC20Viralswap(lastToken).balanceOf(vault); TransferHelper.safeTransferFrom( path[0], msg.sender, address(this), amountIn ); IERC20Viralswap(path[0]).approve(altRouter, amountIn); IUniswapV2Router02(altRouter).swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn, 0, path, vault, deadline ); } uint256 vaultInTransferred = IERC20Viralswap(lastToken).balanceOf(vault).sub(balanceBeforeIn); uint256 balanceBeforeOut = IERC20Viralswap(VIRAL).balanceOf(to); address[] memory fullPath = new address[](2); fullPath[0] = path[path.length - 1]; fullPath[1] = VIRAL; uint256[] memory amounts = new uint[](2); amounts[0] = vaultInTransferred; amounts[1] = ViralswapLibrary.getVaultAmountOut(factory, fullPath[0], fullPath[1], vaultInTransferred); _buy(amounts, fullPath, to); require( IERC20Viralswap(VIRAL).balanceOf(to).sub(balanceBeforeOut) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } /** * @dev Function to buy VIRAL (using the Vault) from an exact amount of ETH * Leverages the `altRouter` for swaps not concerning VIRAL * * @param amountOutMin : the minimum output amount for VIRAL * @param path : [WETH, ..., USDC] * @param to : the address to receive VIRAL * @param deadline : timestamp by which the transaction must complete **/ function buyViralForExactETHSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'ViralswapRouter: INVALID_PATH'); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); uint256 balanceBeforeIn; address lastToken = path[path.length - 1]; address vault = ViralswapLibrary.vaultFor(factory, VIRAL, lastToken); balanceBeforeIn = IERC20Viralswap(lastToken).balanceOf(vault); IERC20Viralswap(path[0]).approve(altRouter, amountIn); IUniswapV2Router02(altRouter).swapExactTokensForTokensSupportingFeeOnTransferTokens( amountIn, 0, path, vault, deadline ); uint256 vaultInTransferred = IERC20Viralswap(lastToken).balanceOf(vault).sub(balanceBeforeIn); uint256 balanceBeforeOut = IERC20Viralswap(VIRAL).balanceOf(to); address[] memory fullPath = new address[](2); fullPath[0] = path[path.length - 1]; fullPath[1] = VIRAL; uint256[] memory amounts = new uint[](2); amounts[0] = vaultInTransferred; amounts[1] = ViralswapLibrary.getVaultAmountOut(factory, fullPath[0], fullPath[1], vaultInTransferred); _buy(amounts, fullPath, to); require( IERC20Viralswap(VIRAL).balanceOf(to).sub(balanceBeforeOut) >= amountOutMin, 'ViralswapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return ViralswapLibrary.quote(amountA, reserveA, reserveB); } function getVaultAmountOut(address tokenIn, address tokenOut, uint amountIn) public view virtual override returns (uint amountOut) { return ViralswapLibrary.getVaultAmountOut(factory, tokenIn, tokenOut, amountIn); } function getVaultAmountIn(address tokenIn, address tokenOut, uint amountOut) public view virtual override returns (uint amountIn) { return ViralswapLibrary.getVaultAmountIn(factory, tokenIn, tokenOut, amountOut); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return ViralswapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return ViralswapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts) { return ViralswapLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts) { return ViralswapLibrary.getAmountsIn(factory, amountOut, path); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import '../interfaces/IViralswapPair.sol'; import '../interfaces/IViralswapVault.sol'; import "./SafeMath.sol"; library ViralswapLibrary { using SafeMathViralswap for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'ViralswapLibrary: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'ViralswapLibrary: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); // pair = IViralswapFactory(factory).getPair(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'2ecb499e264463ecc6eb00e17ca5070ff1178cd8cb97f519faf7a8f28c64d94e' // init code hash )))); } // calculates the CREATE2 address for a vault without making any external calls function vaultFor(address factory, address tokenA, address tokenB) internal pure returns (address vault) { (address token0, address token1) = sortTokens(tokenA, tokenB); // vault = IViralswapFactory(factory).getVault(tokenA, tokenB); vault = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'520f54d5cd1b3378680f5684cdac056d55546dd84b58325ed113e368704b9243' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IViralswapPair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'ViralswapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'ViralswapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset, return the quoted output amount of the other asset function getVaultAmountOut(address factory, address tokenIn, address tokenOut, uint amountIn) internal view returns (uint amountOut) { amountOut = IViralswapVault(vaultFor(factory, tokenIn, tokenOut)).getQuoteOut(tokenIn, amountIn); } // given an output amount of an asset, return the quoted input amount of the other asset function getVaultAmountIn(address factory, address tokenIn, address tokenOut, uint amountOut) internal view returns (uint amountIn) { amountIn = IViralswapVault(vaultFor(factory, tokenIn, tokenOut)).getQuoteIn(tokenOut, amountOut); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'ViralswapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'ViralswapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'ViralswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'ViralswapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ViralswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'ViralswapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMathViralswap { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; import './IUniswapRouter02.sol'; interface IViralswapRouter02 is IUniswapV2Router02 { function swapExactViralForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactViralForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactTokensForViralSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function buyTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function buyViralForExactTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function buyViralForExactETHSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function getVaultAmountOut(address tokenIn, address tokenOut, uint amountIn) external view returns (uint amountOut); function getVaultAmountIn(address tokenIn, address tokenOut, uint amountOut) external view returns (uint amountIn); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; import './IUniswapRouter01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IViralswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function migrator() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function getVault(address tokenA, address tokenB) external view returns (address vault); function allVaults(uint) external view returns (address vault); function allVaultsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function createVault(uint tokenOutPerTokenIn, address tokenIn, address tokenOut, address router, uint feeOnTokenOutTransferBIPS) external returns (address vault); function addQuota(address tokenA, address tokenB, uint quota) external; function updateRouterInVault(address tokenA, address tokenB, address _viralswapRouter02) external; function withdrawERC20FromVault(address tokenA, address tokenB, address tokenToWithdraw, address to) external; function setFeeTo(address) external; function setFeeToSetter(address) external; function setMigrator(address) external; function pairCodeHash() external pure returns (bytes32); function vaultCodeHash() external pure returns (bytes32); function computeProfitMaximizingTrade( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) external pure returns (bool, uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IERC20Viralswap { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IViralswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; interface IViralswapVault { event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function tokenIn() external view returns (address); function tokenOut() external view returns (address); function viralswapRouter02() external view returns (address); function availableQuota() external view returns (uint); function tokenOutPerTokenIn() external view returns (uint); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function getQuoteOut(address _tokenIn, uint _amountIn) external view returns (uint amountOut); function getQuoteIn(address _tokenOut, uint _amountOut) external view returns (uint amountIn); function buy(uint amountOut, address to) external; function sync() external; function initialize(address, address) external; function addQuota(uint) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function VIRAL() external pure returns (address); function altRouter() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); }
given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'ViralswapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'ViralswapLibrary: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; }
10,132,521
./full_match/83/0x1ef4FD8f2C1F0F11F53BB9130d474810Fc49D941/sources/contracts/CToken/CToken.sol
Calculate number of tokens of collateral asset to seize given an underlying amount Used in liquidation (called in ICToken(cToken).liquidateBorrowFresh) cTokenCollateral The address of the collateral cToken actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)/ Read oracle prices for borrowed and collateral markets /
function liquidateCalculateSeizeTokens( address cTokenCollateral, uint256 actualRepayAmount ) public view returns (uint256, uint256) { address oracle = IComptroller(comptroller).oracle(); uint256 priceBorrowedMantissa = IPriceOracle(oracle).getUnderlyingPrice(address(address(this))); uint256 priceCollateralMantissa = IPriceOracle(oracle).getUnderlyingPrice(address(cTokenCollateral)); if (priceBorrowedMantissa <= 0 || priceCollateralMantissa <= 0) { Error.TOKEN_ERROR.fail(FailureInfo.PRICE_ERROR); } Exp memory numerator; Exp memory denominator; Exp memory ratio; ); ratio = numerator.div_(denominator); seizeTokens = ratio.mul_ScalarTruncate(actualRepayAmount); return (uint256(0), seizeTokens); }
9,561,503
pragma solidity 0.5.12; import "./Handler.sol"; import "./library/ReentrancyGuard.sol"; import "./interface/IAave.sol"; contract AaveHandler is Handler, ReentrancyGuard { address public aaveLendingPool; address public aaveLendingPoolCore; // mapping(address => uint256) public interestDetails; struct InterestDetails { uint256 totalUnderlyingBalance; // Total underlying balance including interest uint256 interest; // Total interest } // Based on underlying token, get current interest details mapping(address => InterestDetails) public interestDetails; constructor( address _HNITokenController, address _lendingPool, address _lendingPoolCore ) public { initialize(_HNITokenController, _lendingPool, _lendingPoolCore); } // --- Init --- // This function is used with contract proxy, do not modify this function. function initialize( address _HNITokenController, address _lendingPool, address _lendingPoolCore ) public { super.initialize(_HNITokenController); initReentrancyStatus(); aaveLendingPool = _lendingPool; aaveLendingPoolCore = _lendingPoolCore; } function setLendingPoolCore(address _newLendingPoolCore) external auth { aaveLendingPoolCore = _newLendingPoolCore; } function setLendingPool(address _newLendingPool) external auth { aaveLendingPool = _newLendingPool; } /** * @dev Authorized function to approves market and HNIToken to transfer handler's underlying token. * @param _underlyingToken Token address to approve. */ function approve(address _underlyingToken, uint256 amount) public auth { require( doApprove(_underlyingToken, aaveLendingPoolCore, amount), "approve: Approve aToken failed!" ); super.approve(_underlyingToken, amount); } /** * @dev Deposit token to market, only called by HNIToken contract. * @param _underlyingToken Token to deposit. * @return The actual deposited token amount. */ function deposit(address _underlyingToken, uint256 _amount) external whenNotPaused auth nonReentrant returns (uint256) { require( tokenIsEnabled(_underlyingToken), "deposit: Token is disabled!" ); require( _amount > 0, "deposit: Deposit amount should be greater than 0!" ); address _aToken = getAToken(_underlyingToken); require(_aToken != address(0x0), "deposit: Do not support token!"); uint256 _MarketBalanceBefore = IERC20(_aToken).balanceOf(address(this)); InterestDetails storage _details = interestDetails[_underlyingToken]; // Update the stored interest with the market balance after the mint uint256 _interest = _MarketBalanceBefore.sub( _details.totalUnderlyingBalance ); _details.interest = _details.interest.add(_interest); // Mint all the token balance of the handler, // which should be the exact deposit amount normally, // but there could be some unexpected transfers before. uint256 _handlerBalance = IERC20(_underlyingToken).balanceOf( address(this) ); LendingPool(aaveLendingPool).deposit( _underlyingToken, _handlerBalance, uint16(0) ); // including unexpected transfers. uint256 _MarketBalanceAfter = IERC20(_aToken).balanceOf(address(this)); // Store the latest real balance. _details.totalUnderlyingBalance = _MarketBalanceAfter; uint256 _changedAmount = _MarketBalanceAfter.sub(_MarketBalanceBefore); // return a smaller value as unexpected transfers were also included. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev Withdraw token from market, but only for HNIToken contract. * @param _underlyingToken Token to withdraw. * @param _amount Token amount to withdraw. * @return The actual withdrown token amount. */ function withdraw(address _underlyingToken, uint256 _amount) external whenNotPaused auth nonReentrant returns (uint256) { require( _amount > 0, "withdraw: Withdraw amount should be greater than 0!" ); address _aToken = getAToken(_underlyingToken); require(_aToken != address(0x0), "withdraw: Do not support token!"); uint256 _handlerBalanceBefore = IERC20(_underlyingToken).balanceOf( address(this) ); uint256 _MarketBalanceBefore = IERC20(_aToken).balanceOf(address(this)); InterestDetails storage _details = interestDetails[_underlyingToken]; // Update the stored interest with the market balance after the redeem uint256 _interest = _MarketBalanceBefore.sub( _details.totalUnderlyingBalance ); _details.interest = _details.interest.add(_interest); // aave supports redeem -1 AToken(_aToken).redeem(_amount); uint256 _handlerBalanceAfter = IERC20(_underlyingToken).balanceOf( address(this) ); uint256 _changedAmount = _handlerBalanceAfter.sub( _handlerBalanceBefore ); // including unexpected transfers. uint256 _MarketBalanceAfter = IERC20(_aToken).balanceOf(address(this)); // Store the latest real balance. _details.totalUnderlyingBalance = _MarketBalanceAfter; // return a smaller value. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev The corrsponding AToken address of the _underlyingToken. * @param _underlyingToken Token to query the AToken. */ function getAToken(address _underlyingToken) internal view returns (address) { return LendingPoolCore(aaveLendingPoolCore).getReserveATokenAddress( _underlyingToken ); } /** * @dev Total balance with any accumulated interest for _underlyingToken belonging to handler * @param _underlyingToken Token to get balance. */ function getRealBalance(address _underlyingToken) public view returns (uint256) { return IERC20(getAToken(_underlyingToken)).balanceOf(address(this)); } /** * @dev The maximum withdrawable _underlyingToken in the market. * @param _underlyingToken Token to get liquidity. */ function getRealLiquidity(address _underlyingToken) public view returns (uint256) { uint256 _underlyingBalance = IERC20(getAToken(_underlyingToken)) .balanceOf(address(this)); uint256 _cash = LendingPoolCore(aaveLendingPoolCore) .getReserveAvailableLiquidity(_underlyingToken); return _underlyingBalance > _cash ? _cash : _underlyingBalance; } /***************************************************/ /*** View Interfaces For Backwards compatibility ***/ /***************************************************/ /** * @dev Total balance with any accumulated interest for `_underlyingToken` belonging to `handler`. * @param _underlyingToken Token to get balance. */ function getBalance(address _underlyingToken) external view returns (uint256) { return getRealBalance(_underlyingToken); } /** * @dev The maximum withdrawable amount of token `_underlyingToken` in the market. * @param _underlyingToken Token to get liquidity. */ function getLiquidity(address _underlyingToken) external view returns (uint256) { return getRealLiquidity(_underlyingToken); } }
Authorized function to approves market and HNIToken to transfer handler's underlying token. _underlyingToken Token address to approve./
function approve(address _underlyingToken, uint256 amount) public auth { require( doApprove(_underlyingToken, aaveLendingPoolCore, amount), "approve: Approve aToken failed!" ); super.approve(_underlyingToken, amount); }
2,551,867
/** *Submitted for verification at Etherscan.io on 2021-04-03 */ // SPDX-License-Identifier: BUSL-1.1 // File: @openzeppelin/contracts/utils/EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol 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: contracts/interfaces/IDMMFactory.sol pragma solidity 0.6.12; interface IDMMFactory { function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external returns (address pool); function setFeeConfiguration(address feeTo, uint16 governmentFeeBps) external; function setFeeToSetter(address) external; function getFeeConfiguration() external view returns (address feeTo, uint16 governmentFeeBps); function feeToSetter() external view returns (address); function allPools(uint256) external view returns (address pool); function allPoolsLength() external view returns (uint256); function getUnamplifiedPool(IERC20 token0, IERC20 token1) external view returns (address); function getPools(IERC20 token0, IERC20 token1) external view returns (address[] memory _tokenPools); function isPool( IERC20 token0, IERC20 token1, address pool ) external view returns (bool); } // File: @openzeppelin/contracts/math/SafeMath.sol 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/math/Math.sol 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/utils/ReentrancyGuard.sol 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: @openzeppelin/contracts/utils/Address.sol 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/SafeERC20.sol 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: contracts/libraries/MathExt.sol pragma solidity 0.6.12; library MathExt { using SafeMath for uint256; uint256 public constant PRECISION = (10**18); /// @dev Returns x*y in precision function mulInPrecision(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y) / PRECISION; } /// @dev source: dsMath /// @param xInPrecision should be < PRECISION, so this can not overflow /// @return zInPrecision = (x/PRECISION) ^k * PRECISION function unsafePowInPrecision(uint256 xInPrecision, uint256 k) internal pure returns (uint256 zInPrecision) { require(xInPrecision <= PRECISION, "MathExt: x > PRECISION"); zInPrecision = k % 2 != 0 ? xInPrecision : PRECISION; for (k /= 2; k != 0; k /= 2) { xInPrecision = (xInPrecision * xInPrecision) / PRECISION; if (k % 2 != 0) { zInPrecision = (zInPrecision * xInPrecision) / PRECISION; } } } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) 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; } } } // File: contracts/libraries/FeeFomula.sol pragma solidity 0.6.12; library FeeFomula { using SafeMath for uint256; using MathExt for uint256; uint256 private constant PRECISION = 10**18; uint256 private constant R0 = 1477405064814996100; // 1.4774050648149961 uint256 private constant C0 = (60 * PRECISION) / 10000; uint256 private constant A = uint256(PRECISION * 20000) / 27; uint256 private constant B = uint256(PRECISION * 250) / 9; uint256 private constant C1 = uint256(PRECISION * 985) / 27; uint256 private constant U = (120 * PRECISION) / 100; uint256 private constant G = (836 * PRECISION) / 1000; uint256 private constant F = 5 * PRECISION; uint256 private constant L = (2 * PRECISION) / 10000; // C2 = 25 * PRECISION - (F * (PRECISION - G)**2) / ((PRECISION - G)**2 + L * PRECISION) uint256 private constant C2 = 20036905816356657810; /// @dev calculate fee from rFactorInPrecision, see section 3.2 in dmmSwap white paper /// @dev fee in [15, 60] bps /// @return fee percentage in Precision function getFee(uint256 rFactorInPrecision) internal pure returns (uint256) { if (rFactorInPrecision >= R0) { return C0; } else if (rFactorInPrecision >= PRECISION) { // C1 + A * (r-U)^3 + b * (r -U) if (rFactorInPrecision > U) { uint256 tmp = rFactorInPrecision - U; uint256 tmp3 = tmp.unsafePowInPrecision(3); return (C1.add(A.mulInPrecision(tmp3)).add(B.mulInPrecision(tmp))) / 10000; } else { uint256 tmp = U - rFactorInPrecision; uint256 tmp3 = tmp.unsafePowInPrecision(3); return C1.sub(A.mulInPrecision(tmp3)).sub(B.mulInPrecision(tmp)) / 10000; } } else { // [ C2 + sign(r - G) * F * (r-G) ^2 / (L + (r-G) ^2) ] / 10000 uint256 tmp = ( rFactorInPrecision > G ? (rFactorInPrecision - G) : (G - rFactorInPrecision) ); tmp = tmp.unsafePowInPrecision(2); uint256 tmp2 = F.mul(tmp).div(tmp.add(L)); if (rFactorInPrecision > G) { return C2.add(tmp2) / 10000; } else { return C2.sub(tmp2) / 10000; } } } } // File: @openzeppelin/contracts/utils/Context.sol 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/token/ERC20/ERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/interfaces/IERC20Permit.sol pragma solidity 0.6.12; interface IERC20Permit is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File: contracts/libraries/ERC20Permit.sol pragma solidity 0.6.12; /// @dev https://eips.ethereum.org/EIPS/eip-2612 contract ERC20Permit is ERC20, IERC20Permit { /// @dev To make etherscan auto-verify new pool, this variable is not immutable bytes32 public domainSeparator; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public nonces; constructor( string memory name, string memory symbol, string memory version ) public ERC20(name, symbol) { uint256 chainId; assembly { chainId := chainid() } domainSeparator = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { require(deadline >= block.timestamp, "ERC20Permit: EXPIRED"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "ERC20Permit: INVALID_SIGNATURE" ); _approve(owner, spender, value); } } // File: contracts/interfaces/IDMMCallee.sol pragma solidity 0.6.12; interface IDMMCallee { function dmmSwapCall( address sender, uint256 amount0, uint256 amount1, bytes calldata data ) external; } // File: contracts/interfaces/IDMMPool.sol pragma solidity 0.6.12; interface IDMMPool { function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function sync() external; function getReserves() external view returns (uint112 reserve0, uint112 reserve1); function getTradeInfo() external view returns ( uint112 _vReserve0, uint112 _vReserve1, uint112 reserve0, uint112 reserve1, uint256 feeInPrecision ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function ampBps() external view returns (uint32); function factory() external view returns (IDMMFactory); function kLast() external view returns (uint256); } // File: contracts/interfaces/IERC20Metadata.sol pragma solidity 0.6.12; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: contracts/VolumeTrendRecorder.sol pragma solidity 0.6.12; /// @dev contract to calculate volume trend. See secion 3.1 in the white paper /// @dev EMA stands for Exponential moving average /// @dev https://en.wikipedia.org/wiki/Moving_average contract VolumeTrendRecorder { using MathExt for uint256; using SafeMath for uint256; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 internal constant PRECISION = 10**18; uint256 private constant SHORT_ALPHA = (2 * PRECISION) / 5401; uint256 private constant LONG_ALPHA = (2 * PRECISION) / 10801; uint128 internal shortEMA; uint128 internal longEMA; // total volume in current block uint128 internal currentBlockVolume; uint128 internal lastTradeBlock; event UpdateEMA(uint256 shortEMA, uint256 longEMA, uint128 lastBlockVolume, uint256 skipBlock); constructor(uint128 _emaInit) public { shortEMA = _emaInit; longEMA = _emaInit; lastTradeBlock = safeUint128(block.number); } function getVolumeTrendData() external view returns ( uint128 _shortEMA, uint128 _longEMA, uint128 _currentBlockVolume, uint128 _lastTradeBlock ) { _shortEMA = shortEMA; _longEMA = longEMA; _currentBlockVolume = currentBlockVolume; _lastTradeBlock = lastTradeBlock; } /// @dev records a new trade, update ema and returns current rFactor for this trade /// @return rFactor in Precision for this trade function recordNewUpdatedVolume(uint256 blockNumber, uint256 value) internal returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { currentBlockVolume = safeUint128( uint256(currentBlockVolume).add(value), "volume exceeds valid range" ); return calculateRFactor(uint256(shortEMA), uint256(longEMA)); } uint128 _currentBlockVolume = currentBlockVolume; uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); // ema = ema * (1-aplha) ^(skipBlock -1) _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); shortEMA = safeUint128(_shortEMA); longEMA = safeUint128(_longEMA); currentBlockVolume = safeUint128(value); lastTradeBlock = safeUint128(blockNumber); emit UpdateEMA(_shortEMA, _longEMA, _currentBlockVolume, skipBlock); return calculateRFactor(_shortEMA, _longEMA); } /// @return rFactor in Precision for this trade function getRFactor(uint256 blockNumber) internal view returns (uint256) { // this can not be underflow because block.number always increases uint256 skipBlock = blockNumber - lastTradeBlock; if (skipBlock == 0) { return calculateRFactor(shortEMA, longEMA); } uint256 _shortEMA = newEMA(shortEMA, SHORT_ALPHA, currentBlockVolume); uint256 _longEMA = newEMA(longEMA, LONG_ALPHA, currentBlockVolume); _shortEMA = _shortEMA.mulInPrecision( (PRECISION - SHORT_ALPHA).unsafePowInPrecision(skipBlock - 1) ); _longEMA = _longEMA.mulInPrecision( (PRECISION - LONG_ALPHA).unsafePowInPrecision(skipBlock - 1) ); return calculateRFactor(_shortEMA, _longEMA); } function calculateRFactor(uint256 _shortEMA, uint256 _longEMA) internal pure returns (uint256) { if (_longEMA == 0) { return 0; } return (_shortEMA * MathExt.PRECISION) / _longEMA; } /// @dev return newEMA value /// @param ema previous ema value in wei /// @param alpha in Precicion (required < Precision) /// @param value current value to update ema /// @dev ema and value is uint128 and alpha < Percison /// @dev so this function can not overflow and returned ema is not overflow uint128 function newEMA( uint128 ema, uint256 alpha, uint128 value ) internal pure returns (uint256) { assert(alpha < PRECISION); return ((PRECISION - alpha) * uint256(ema) + alpha * uint256(value)) / PRECISION; } function safeUint128(uint256 v) internal pure returns (uint128) { require(v <= MAX_UINT128, "overflow uint128"); return uint128(v); } function safeUint128(uint256 v, string memory errorMessage) internal pure returns (uint128) { require(v <= MAX_UINT128, errorMessage); return uint128(v); } } // File: contracts/DMMPool.sol pragma solidity 0.6.12; contract DMMPool is IDMMPool, ERC20Permit, ReentrancyGuard, VolumeTrendRecorder { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 internal constant MAX_UINT112 = 2**112 - 1; uint256 internal constant BPS = 10000; struct ReserveData { uint256 reserve0; uint256 reserve1; uint256 vReserve0; uint256 vReserve1; // only used when isAmpPool = true } uint256 public constant MINIMUM_LIQUIDITY = 10**3; /// @dev To make etherscan auto-verify new pool, these variables are not immutable IDMMFactory public override factory; IERC20 public override token0; IERC20 public override token1; /// @dev uses single storage slot, accessible via getReservesData uint112 internal reserve0; uint112 internal reserve1; uint32 public override ampBps; /// @dev addition param only when amplification factor > 1 uint112 internal vReserve0; uint112 internal vReserve1; /// @dev vReserve0 * vReserve1, as of immediately after the most recent liquidity event uint256 public override kLast; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to, uint256 feeInPrecision ); event Sync(uint256 vReserve0, uint256 vReserve1, uint256 reserve0, uint256 reserve1); constructor() public ERC20Permit("KyberDMM LP", "DMM-LP", "1") VolumeTrendRecorder(0) { factory = IDMMFactory(msg.sender); } // called once by the factory at time of deployment function initialize( IERC20 _token0, IERC20 _token1, uint32 _ampBps ) external { require(msg.sender == address(factory), "DMM: FORBIDDEN"); token0 = _token0; token1 = _token1; ampBps = _ampBps; } /// @dev this low-level function should be called from a contract /// which performs important safety checks function mint(address to) external override nonReentrant returns (uint256 liquidity) { (bool isAmpPool, ReserveData memory data) = getReservesData(); ReserveData memory _data; _data.reserve0 = token0.balanceOf(address(this)); _data.reserve1 = token1.balanceOf(address(this)); uint256 amount0 = _data.reserve0.sub(data.reserve0); uint256 amount1 = _data.reserve1.sub(data.reserve1); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { if (isAmpPool) { uint32 _ampBps = ampBps; _data.vReserve0 = _data.reserve0.mul(_ampBps) / BPS; _data.vReserve1 = _data.reserve1.mul(_ampBps) / BPS; } liquidity = MathExt.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(-1), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min( amount0.mul(_totalSupply) / data.reserve0, amount1.mul(_totalSupply) / data.reserve1 ); if (isAmpPool) { uint256 b = liquidity.add(_totalSupply); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } } require(liquidity > 0, "DMM: INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); emit Mint(msg.sender, amount0, amount1); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks /// @dev user must transfer LP token to this contract before call burn function burn(address to) external override nonReentrant returns (uint256 amount0, uint256 amount1) { (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings IERC20 _token0 = token0; // gas savings IERC20 _token1 = token1; // gas savings uint256 balance0 = _token0.balanceOf(address(this)); uint256 balance1 = _token1.balanceOf(address(this)); require(balance0 >= data.reserve0 && balance1 >= data.reserve1, "DMM: UNSYNC_RESERVES"); uint256 liquidity = balanceOf(address(this)); bool feeOn = _mintFee(isAmpPool, data); uint256 _totalSupply = totalSupply(); // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, "DMM: INSUFFICIENT_LIQUIDITY_BURNED"); _burn(address(this), liquidity); _token0.safeTransfer(to, amount0); _token1.safeTransfer(to, amount1); ReserveData memory _data; _data.reserve0 = _token0.balanceOf(address(this)); _data.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { uint256 b = Math.min( _data.reserve0.mul(_totalSupply) / data.reserve0, _data.reserve1.mul(_totalSupply) / data.reserve1 ); _data.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, _data.reserve0); _data.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, _data.reserve1); } _update(isAmpPool, _data); if (feeOn) kLast = getK(isAmpPool, _data); // data are up-to-date emit Burn(msg.sender, amount0, amount1, to); } /// @dev this low-level function should be called from a contract /// @dev which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata callbackData ) external override nonReentrant { require(amount0Out > 0 || amount1Out > 0, "DMM: INSUFFICIENT_OUTPUT_AMOUNT"); (bool isAmpPool, ReserveData memory data) = getReservesData(); // gas savings require( amount0Out < data.reserve0 && amount1Out < data.reserve1, "DMM: INSUFFICIENT_LIQUIDITY" ); ReserveData memory newData; { // scope for _token{0,1}, avoids stack too deep errors IERC20 _token0 = token0; IERC20 _token1 = token1; require(to != address(_token0) && to != address(_token1), "DMM: INVALID_TO"); if (amount0Out > 0) _token0.safeTransfer(to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _token1.safeTransfer(to, amount1Out); // optimistically transfer tokens if (callbackData.length > 0) IDMMCallee(to).dmmSwapCall(msg.sender, amount0Out, amount1Out, callbackData); newData.reserve0 = _token0.balanceOf(address(this)); newData.reserve1 = _token1.balanceOf(address(this)); if (isAmpPool) { newData.vReserve0 = data.vReserve0.add(newData.reserve0).sub(data.reserve0); newData.vReserve1 = data.vReserve1.add(newData.reserve1).sub(data.reserve1); } } uint256 amount0In = newData.reserve0 > data.reserve0 - amount0Out ? newData.reserve0 - (data.reserve0 - amount0Out) : 0; uint256 amount1In = newData.reserve1 > data.reserve1 - amount1Out ? newData.reserve1 - (data.reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, "DMM: INSUFFICIENT_INPUT_AMOUNT"); uint256 feeInPrecision = verifyBalanceAndUpdateEma( amount0In, amount1In, isAmpPool ? data.vReserve0 : data.reserve0, isAmpPool ? data.vReserve1 : data.reserve1, isAmpPool ? newData.vReserve0 : newData.reserve0, isAmpPool ? newData.vReserve1 : newData.reserve1 ); _update(isAmpPool, newData); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to, feeInPrecision); } /// @dev force balances to match reserves function skim(address to) external nonReentrant { token0.safeTransfer(to, token0.balanceOf(address(this)).sub(reserve0)); token1.safeTransfer(to, token1.balanceOf(address(this)).sub(reserve1)); } /// @dev force reserves to match balances function sync() external override nonReentrant { (bool isAmpPool, ReserveData memory data) = getReservesData(); bool feeOn = _mintFee(isAmpPool, data); ReserveData memory newData; newData.reserve0 = IERC20(token0).balanceOf(address(this)); newData.reserve1 = IERC20(token1).balanceOf(address(this)); // update virtual reserves if this is amp pool if (isAmpPool) { uint256 _totalSupply = totalSupply(); uint256 b = Math.min( newData.reserve0.mul(_totalSupply) / data.reserve0, newData.reserve1.mul(_totalSupply) / data.reserve1 ); newData.vReserve0 = Math.max(data.vReserve0.mul(b) / _totalSupply, newData.reserve0); newData.vReserve1 = Math.max(data.vReserve1.mul(b) / _totalSupply, newData.reserve1); } _update(isAmpPool, newData); if (feeOn) kLast = getK(isAmpPool, newData); } /// @dev returns data to calculate amountIn, amountOut function getTradeInfo() external virtual override view returns ( uint112 _reserve0, uint112 _reserve1, uint112 _vReserve0, uint112 _vReserve1, uint256 feeInPrecision ) { // gas saving to read reserve data _reserve0 = reserve0; _reserve1 = reserve1; uint32 _ampBps = ampBps; _vReserve0 = vReserve0; _vReserve1 = vReserve1; if (_ampBps == BPS) { _vReserve0 = _reserve0; _vReserve1 = _reserve1; } uint256 rFactorInPrecision = getRFactor(block.number); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), _ampBps); } /// @dev returns reserve data to calculate amount to add liquidity function getReserves() external override view returns (uint112 _reserve0, uint112 _reserve1) { _reserve0 = reserve0; _reserve1 = reserve1; } function name() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("KyberDMM LP ", _token0.symbol(), "-", _token1.symbol())); } function symbol() public override view returns (string memory) { IERC20Metadata _token0 = IERC20Metadata(address(token0)); IERC20Metadata _token1 = IERC20Metadata(address(token1)); return string(abi.encodePacked("DMM-LP ", _token0.symbol(), "-", _token1.symbol())); } function verifyBalanceAndUpdateEma( uint256 amount0In, uint256 amount1In, uint256 beforeReserve0, uint256 beforeReserve1, uint256 afterReserve0, uint256 afterReserve1 ) internal virtual returns (uint256 feeInPrecision) { // volume = beforeReserve0 * amount1In / beforeReserve1 + amount0In (normalized into amount in token 0) uint256 volume = beforeReserve0.mul(amount1In).div(beforeReserve1).add(amount0In); uint256 rFactorInPrecision = recordNewUpdatedVolume(block.number, volume); feeInPrecision = getFinalFee(FeeFomula.getFee(rFactorInPrecision), ampBps); // verify balance update matches with fomula uint256 balance0Adjusted = afterReserve0.mul(PRECISION); balance0Adjusted = balance0Adjusted.sub(amount0In.mul(feeInPrecision)); balance0Adjusted = balance0Adjusted / PRECISION; uint256 balance1Adjusted = afterReserve1.mul(PRECISION); balance1Adjusted = balance1Adjusted.sub(amount1In.mul(feeInPrecision)); balance1Adjusted = balance1Adjusted / PRECISION; require( balance0Adjusted.mul(balance1Adjusted) >= beforeReserve0.mul(beforeReserve1), "DMM: K" ); } /// @dev update reserves function _update(bool isAmpPool, ReserveData memory data) internal { reserve0 = safeUint112(data.reserve0); reserve1 = safeUint112(data.reserve1); if (isAmpPool) { assert(data.vReserve0 >= data.reserve0 && data.vReserve1 >= data.reserve1); // never happen vReserve0 = safeUint112(data.vReserve0); vReserve1 = safeUint112(data.vReserve1); } emit Sync(data.vReserve0, data.vReserve1, data.reserve0, data.reserve1); } /// @dev if fee is on, mint liquidity equivalent to configured fee of the growth in sqrt(k) function _mintFee(bool isAmpPool, ReserveData memory data) internal returns (bool feeOn) { (address feeTo, uint16 governmentFeeBps) = factory.getFeeConfiguration(); feeOn = feeTo != address(0); uint256 _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint256 rootK = MathExt.sqrt(getK(isAmpPool, data)); uint256 rootKLast = MathExt.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply().mul(rootK.sub(rootKLast)).mul( governmentFeeBps ); uint256 denominator = rootK.add(rootKLast).mul(5000); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } /// @dev gas saving to read reserve data function getReservesData() internal view returns (bool isAmpPool, ReserveData memory data) { data.reserve0 = reserve0; data.reserve1 = reserve1; isAmpPool = ampBps != BPS; if (isAmpPool) { data.vReserve0 = vReserve0; data.vReserve1 = vReserve1; } } function getFinalFee(uint256 feeInPrecision, uint32 _ampBps) internal pure returns (uint256) { if (_ampBps <= 20000) { return feeInPrecision; } else if (_ampBps <= 50000) { return (feeInPrecision * 20) / 30; } else if (_ampBps <= 200000) { return (feeInPrecision * 10) / 30; } else { return (feeInPrecision * 4) / 30; } } function getK(bool isAmpPool, ReserveData memory data) internal pure returns (uint256) { return isAmpPool ? data.vReserve0 * data.vReserve1 : data.reserve0 * data.reserve1; } function safeUint112(uint256 x) internal pure returns (uint112) { require(x <= MAX_UINT112, "DMM: OVERFLOW"); return uint112(x); } } // File: contracts/DMMFactory.sol pragma solidity 0.6.12; contract DMMFactory is IDMMFactory { using EnumerableSet for EnumerableSet.AddressSet; uint256 internal constant BPS = 10000; address private feeTo; uint16 private governmentFeeBps; address public override feeToSetter; mapping(IERC20 => mapping(IERC20 => EnumerableSet.AddressSet)) internal tokenPools; mapping(IERC20 => mapping(IERC20 => address)) public override getUnamplifiedPool; address[] public override allPools; event PoolCreated( IERC20 indexed token0, IERC20 indexed token1, address pool, uint32 ampBps, uint256 totalPool ); event SetFeeConfiguration(address feeTo, uint16 governmentFeeBps); event SetFeeToSetter(address feeToSetter); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function createPool( IERC20 tokenA, IERC20 tokenB, uint32 ampBps ) external override returns (address pool) { require(tokenA != tokenB, "DMM: IDENTICAL_ADDRESSES"); (IERC20 token0, IERC20 token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(address(token0) != address(0), "DMM: ZERO_ADDRESS"); require(ampBps >= BPS, "DMM: INVALID_BPS"); // only exist 1 unamplified pool of a pool. require( ampBps != BPS || getUnamplifiedPool[token0][token1] == address(0), "DMM: UNAMPLIFIED_POOL_EXISTS" ); pool = address(new DMMPool()); DMMPool(pool).initialize(token0, token1, ampBps); // populate mapping in the reverse direction tokenPools[token0][token1].add(pool); tokenPools[token1][token0].add(pool); if (ampBps == BPS) { getUnamplifiedPool[token0][token1] = pool; getUnamplifiedPool[token1][token0] = pool; } allPools.push(pool); emit PoolCreated(token0, token1, pool, ampBps, allPools.length); } function setFeeConfiguration(address _feeTo, uint16 _governmentFeeBps) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); require(_governmentFeeBps > 0 && _governmentFeeBps < 2000, "DMM: INVALID FEE"); feeTo = _feeTo; governmentFeeBps = _governmentFeeBps; emit SetFeeConfiguration(_feeTo, _governmentFeeBps); } function setFeeToSetter(address _feeToSetter) external override { require(msg.sender == feeToSetter, "DMM: FORBIDDEN"); feeToSetter = _feeToSetter; emit SetFeeToSetter(_feeToSetter); } function getFeeConfiguration() external override view returns (address _feeTo, uint16 _governmentFeeBps) { _feeTo = feeTo; _governmentFeeBps = governmentFeeBps; } function allPoolsLength() external override view returns (uint256) { return allPools.length; } function getPools(IERC20 token0, IERC20 token1) external override view returns (address[] memory _tokenPools) { uint256 length = tokenPools[token0][token1].length(); _tokenPools = new address[](length); for (uint256 i = 0; i < length; i++) { _tokenPools[i] = tokenPools[token0][token1].at(i); } } function getPoolsLength(IERC20 token0, IERC20 token1) external view returns (uint256) { return tokenPools[token0][token1].length(); } function getPoolAtIndex( IERC20 token0, IERC20 token1, uint256 index ) external view returns (address pool) { return tokenPools[token0][token1].at(index); } function isPool( IERC20 token0, IERC20 token1, address pool ) external override view returns (bool) { return tokenPools[token0][token1].contains(pool); } }
called once by the factory at time of deployment
function initialize( IERC20 _token0, IERC20 _token1, uint32 _ampBps ) external { require(msg.sender == address(factory), "DMM: FORBIDDEN"); token0 = _token0; token1 = _token1; ampBps = _ampBps; }
2,135,916
//Address: 0xc350ebf34b6d83b64ea0ee4e39b6ebe18f02ad2f //Contract name: ExpiringMarket //Balance: 0 Ether //Verification Date: 2/28/2017 //Transacion Count: 3073 // CODE STARTS HERE /* Copyright 2016, 2017 Nexus Development, LLC 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.4.8; // Token standard API // https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function totalSupply() constant returns (uint supply); function balanceOf( address who ) constant returns (uint value); function allowance( address owner, address spender ) constant returns (uint _allowance); function transfer( address to, uint value) returns (bool ok); function transferFrom( address from, address to, uint value) returns (bool ok); function approve( address spender, uint value ) returns (bool ok); event Transfer( address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } contract EventfulMarket { event ItemUpdate( uint id ); event Trade( uint sell_how_much, address indexed sell_which_token, uint buy_how_much, address indexed buy_which_token ); event LogMake( bytes32 indexed id, bytes32 indexed pair, address indexed maker, ERC20 haveToken, ERC20 wantToken, uint128 haveAmount, uint128 wantAmount, uint64 timestamp ); event LogTake( bytes32 id, bytes32 indexed pair, address indexed maker, ERC20 haveToken, ERC20 wantToken, address indexed taker, uint128 takeAmount, uint128 giveAmount, uint64 timestamp ); event LogKill( bytes32 indexed id, bytes32 indexed pair, address indexed maker, ERC20 haveToken, ERC20 wantToken, uint128 haveAmount, uint128 wantAmount, uint64 timestamp ); } contract SimpleMarket is EventfulMarket { bool locked; modifier synchronized { assert(!locked); locked = true; _; locked = false; } function assert(bool x) internal { if (!x) throw; } struct OfferInfo { uint sell_how_much; ERC20 sell_which_token; uint buy_how_much; ERC20 buy_which_token; address owner; bool active; } mapping (uint => OfferInfo) public offers; uint public last_offer_id; function next_id() internal returns (uint) { last_offer_id++; return last_offer_id; } modifier can_offer { _; } modifier can_buy(uint id) { assert(isActive(id)); _; } modifier can_cancel(uint id) { assert(isActive(id)); assert(getOwner(id) == msg.sender); _; } function isActive(uint id) constant returns (bool active) { return offers[id].active; } function getOwner(uint id) constant returns (address owner) { return offers[id].owner; } function getOffer( uint id ) constant returns (uint, ERC20, uint, ERC20) { var offer = offers[id]; return (offer.sell_how_much, offer.sell_which_token, offer.buy_how_much, offer.buy_which_token); } // non underflowing subtraction function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } // non overflowing multiplication function safeMul(uint a, uint b) internal returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } function trade( address seller, uint sell_how_much, ERC20 sell_which_token, address buyer, uint buy_how_much, ERC20 buy_which_token ) internal { var seller_paid_out = buy_which_token.transferFrom( buyer, seller, buy_how_much ); assert(seller_paid_out); var buyer_paid_out = sell_which_token.transfer( buyer, sell_how_much ); assert(buyer_paid_out); Trade( sell_how_much, sell_which_token, buy_how_much, buy_which_token ); } // ---- Public entrypoints ---- // function make( ERC20 haveToken, ERC20 wantToken, uint128 haveAmount, uint128 wantAmount ) returns (bytes32 id) { return bytes32(offer(haveAmount, haveToken, wantAmount, wantToken)); } function take(bytes32 id, uint128 maxTakeAmount) { assert(buy(uint256(id), maxTakeAmount)); } function kill(bytes32 id) { assert(cancel(uint256(id))); } // Make a new offer. Takes funds from the caller into market escrow. function offer( uint sell_how_much, ERC20 sell_which_token , uint buy_how_much, ERC20 buy_which_token ) can_offer synchronized returns (uint id) { assert(uint128(sell_how_much) == sell_how_much); assert(uint128(buy_how_much) == buy_how_much); assert(sell_how_much > 0); assert(sell_which_token != ERC20(0x0)); assert(buy_how_much > 0); assert(buy_which_token != ERC20(0x0)); assert(sell_which_token != buy_which_token); OfferInfo memory info; info.sell_how_much = sell_how_much; info.sell_which_token = sell_which_token; info.buy_how_much = buy_how_much; info.buy_which_token = buy_which_token; info.owner = msg.sender; info.active = true; id = next_id(); offers[id] = info; var seller_paid = sell_which_token.transferFrom( msg.sender, this, sell_how_much ); assert(seller_paid); ItemUpdate(id); LogMake( bytes32(id), sha3(sell_which_token, buy_which_token), msg.sender, sell_which_token, buy_which_token, uint128(sell_how_much), uint128(buy_how_much), uint64(now) ); } // Accept given `quantity` of an offer. Transfers funds from caller to // offer maker, and from market to caller. function buy( uint id, uint quantity ) can_buy(id) synchronized returns ( bool success ) { assert(uint128(quantity) == quantity); // read-only offer. Modify an offer by directly accessing offers[id] OfferInfo memory offer = offers[id]; // inferred quantity that the buyer wishes to spend uint spend = safeMul(quantity, offer.buy_how_much) / offer.sell_how_much; assert(uint128(spend) == spend); if ( spend > offer.buy_how_much || quantity > offer.sell_how_much ) { // buyer wants more than is available success = false; } else if ( spend == offer.buy_how_much && quantity == offer.sell_how_much ) { // buyer wants exactly what is available delete offers[id]; trade( offer.owner, quantity, offer.sell_which_token, msg.sender, spend, offer.buy_which_token ); ItemUpdate(id); LogTake( bytes32(id), sha3(offer.sell_which_token, offer.buy_which_token), offer.owner, offer.sell_which_token, offer.buy_which_token, msg.sender, uint128(offer.sell_how_much), uint128(offer.buy_how_much), uint64(now) ); success = true; } else if ( spend > 0 && quantity > 0 ) { // buyer wants a fraction of what is available offers[id].sell_how_much = safeSub(offer.sell_how_much, quantity); offers[id].buy_how_much = safeSub(offer.buy_how_much, spend); trade( offer.owner, quantity, offer.sell_which_token, msg.sender, spend, offer.buy_which_token ); ItemUpdate(id); LogTake( bytes32(id), sha3(offer.sell_which_token, offer.buy_which_token), offer.owner, offer.sell_which_token, offer.buy_which_token, msg.sender, uint128(quantity), uint128(spend), uint64(now) ); success = true; } else { // buyer wants an unsatisfiable amount (less than 1 integer) success = false; } } // Cancel an offer. Refunds offer maker. function cancel( uint id ) can_cancel(id) synchronized returns ( bool success ) { // read-only offer. Modify an offer by directly accessing offers[id] OfferInfo memory offer = offers[id]; delete offers[id]; var seller_refunded = offer.sell_which_token.transfer( offer.owner , offer.sell_how_much ); assert(seller_refunded); ItemUpdate(id); LogKill( bytes32(id), sha3(offer.sell_which_token, offer.buy_which_token), offer.owner, offer.sell_which_token, offer.buy_which_token, uint128(offer.sell_how_much), uint128(offer.buy_how_much), uint64(now) ); success = true; } } // Simple Market with a market lifetime. When the lifetime has elapsed, // offers can only be cancelled (offer and buy will throw). contract ExpiringMarket is SimpleMarket { uint public lifetime; uint public close_time; function ExpiringMarket(uint lifetime_) { lifetime = lifetime_; close_time = getTime() + lifetime_; } function getTime() constant returns (uint) { return block.timestamp; } function isClosed() constant returns (bool closed) { return (getTime() > close_time); } // after market lifetime has elapsed, no new offers are allowed modifier can_offer { assert(!isClosed()); _; } // after close, no new buys are allowed modifier can_buy(uint id) { assert(isActive(id)); assert(!isClosed()); _; } // after close, anyone can cancel an offer modifier can_cancel(uint id) { assert(isActive(id)); assert(isClosed() || (msg.sender == getOwner(id))); _; } }
Cancel an offer. Refunds offer maker. read-only offer. Modify an offer by directly accessing offers[id]
function cancel( uint id ) can_cancel(id) synchronized returns ( bool success ) { OfferInfo memory offer = offers[id]; delete offers[id]; var seller_refunded = offer.sell_which_token.transfer( offer.owner , offer.sell_how_much ); assert(seller_refunded); ItemUpdate(id); LogKill( bytes32(id), sha3(offer.sell_which_token, offer.buy_which_token), offer.owner, offer.sell_which_token, offer.buy_which_token, uint128(offer.sell_how_much), uint128(offer.buy_how_much), uint64(now) ); success = true; }
13,109,539
import "./owned.sol"; import "./localsCointoken.sol"; //onlyReputable contract localsInOut is owned { event OfferAdded(uint offerID, uint amount,uint validityStart,uint duration, string descriptionipfs); event Confirmed(uint offerNumber, bool supportsProposal, address confirmator); event OfferClaimed(uint offerNumber, address claimer, address creator, uint amount); Offer[] public offers; uint public numOffers; struct Offer { address creator; address claimer; uint amount; // amount of localcoin string descriptionipfs; // uint validityStart; uint validityEnd; uint status; uint geoMapping; uint duration; uint numberOfConfirmations; /* 0: Created, 1: Live, 2: Claimed, 3: Executed, 4: Validated, 5: Expired */ Confirmation[] confirmations; mapping (address => bool) confirmed; } struct Confirmation { bool inSupport; address voter; } /*modifier onlyReputable { if (repCoin.balanceOf(msg.sender) == 0) throw; _ }*/ /* Function to create a new proposal */ function newOffer( //address _claimer, uint _amount, string _descriptionipfs, uint _validityStart, uint _duration ) //onlyReputable returns (uint offerID) { offerID = offers.length++; Offer o = offers[offerID]; o.creator = msg.sender; //o.claimer = _claimer; o.amount = _amount; o.descriptionipfs = _descriptionipfs; o.validityStart = _validityStart; o.validityEnd = now + _duration * 1 minutes; o.status = 0; o.numberOfConfirmations = 0; OfferAdded(offerID, _amount,_validityStart,_duration, _descriptionipfs); numOffers = offerID+1; } function claim(uint offerNumber) { Offer o = offers[offerNumber]; if(msg.value==o.amount){ o.claimer = msg.sender; o.status = 2; OfferClaimed(offerNumber, o.claimer, o.creator, o.amount); } } /* */ function confirm(uint offerNumber, bool supportsConfirmation) /*onlyReputable*/ returns (uint confirmID) { Offer o = offers[offerNumber]; if (o.confirmed[msg.sender] == true) throw; confirmID = o.confirmations.length++; o.confirmations[confirmID] = Confirmation({inSupport: supportsConfirmation, voter: msg.sender}); o.confirmed[msg.sender] = true; o.numberOfConfirmations = confirmID +1; Confirmed(offerNumber, supportsConfirmation, msg.sender); } function executeOffer(uint offerNumber, bytes transactionBytecode) returns (int result) { Offer o = offers[offerNumber]; // amount 1% to DAO and rest send to claimer } function kill() { if (msg.sender == owner) suicide(owner); } }
amount 1% to DAO and rest send to claimer
function executeOffer(uint offerNumber, bytes transactionBytecode) returns (int result) { Offer o = offers[offerNumber]; }
5,546,532
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol
Reverts the current transaction with an "InvalidTime" error message. startTime The time at which the order becomes active. endTime The time at which the order becomes inactive./
function _revertInvalidTime(uint256 startTime, uint256 endTime) pure { assembly { mstore(0, InvalidTime_error_selector) mstore(InvalidTime_error_startTime_ptr, startTime) mstore(InvalidTime_error_endTime_ptr, endTime) revert(Error_selector_offset, InvalidTime_error_length) } }
4,301,443
pragma solidity 0.5.7; pragma experimental ABIEncoderV2; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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, "SafeMath::mul: Integer overflow"); 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, "SafeMath::div: Invalid divisor zero"); 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, "SafeMath::sub: Integer underflow"); 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, "SafeMath::add: Integer overflow"); 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, "SafeMath::mod: Invalid divisor zero"); return a % b; } } contract IHumanity { function mint(address account, uint256 value) public; function totalSupply() public view returns (uint256); } /** * @title HumanityRegistry * @dev A list of Ethereum addresses that belong to unique humans as determined by Humanity governance. */ contract HumanityRegistry { mapping (address => bool) public humans; IHumanity public humanity; address public governance; constructor(IHumanity _humanity, address _governance) public { humanity = _humanity; governance = _governance; } function add(address who) public { require(msg.sender == governance, "HumanityRegistry::add: Only governance can add an identity"); require(humans[who] == false, "HumanityRegistry::add: Address is already on the registry"); _reward(who); humans[who] = true; } function remove(address who) public { require( msg.sender == governance || msg.sender == who, "HumanityRegistry::remove: Only governance or the identity owner can remove an identity" ); delete humans[who]; } function isHuman(address who) public view returns (bool) { return humans[who]; } function _reward(address who) internal { uint totalSupply = humanity.totalSupply(); if (totalSupply < 28000000e18) { humanity.mint(who, 30000e18); // 1 - 100 } else if (totalSupply < 46000000e18) { humanity.mint(who, 20000e18); // 101 - 1000 } else if (totalSupply < 100000000e18) { humanity.mint(who, 6000e18); // 1001 - 10000 } } } /** * @title UniversalBasicIncome * @dev Dai that can be claimed by humans on the Human Registry. */ contract UniversalBasicIncome { using SafeMath for uint; HumanityRegistry public registry; IERC20 public dai; uint public constant MONTHLY_INCOME = 1e18; // 1 Dai uint public constant INCOME_PER_SECOND = MONTHLY_INCOME / 30 days; mapping (address => uint) public claimTimes; constructor(HumanityRegistry _registry, IERC20 _dai) public { registry = _registry; dai = _dai; } function claim() public { require(registry.isHuman(msg.sender), "UniversalBasicIncome::claim: You must be on the Humanity registry to claim income"); uint income; uint time = block.timestamp; // If claiming for the first time, send 1 month of UBI if (claimTimes[msg.sender] == 0) { income = MONTHLY_INCOME; } else { income = time.sub(claimTimes[msg.sender]).mul(INCOME_PER_SECOND); } uint balance = dai.balanceOf(address(this)); // If not enough Dai reserves, send the remaining balance uint actualIncome = balance < income ? balance : income; dai.transfer(msg.sender, actualIncome); claimTimes[msg.sender] = time; } }
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, "SafeMath::mod: Invalid divisor zero"); return a % b; }
1,773,235
./partial_match/1/0xD0C6e59B50C32530C627107F50Acc71958C4341F/sources/contracts/loans/direct/loanTypes/DirectLoanBaseMinimal.sol
Resolving the loan without trasferring the nft to provide a base for the bundle break up of the bundled loans _loanId A unique identifier for this particular loan, sourced from the Loan Coordinator. _loanTerms - The main Loan Terms struct. This data is saved upon loan creation on loanIdToLoan. _loanCoordinator - The loan coordinator used when creating the loan./ Mark loan as liquidated before doing any external transfers to follow the Checks-Effects-Interactions design pattern Destroy the lender's promissory note for this loan and borrower obligation receipt
function _resolveLoanNoNftTransfer( uint32 _loanId, LoanTerms memory _loanTerms, IDirectLoanCoordinator _loanCoordinator, bool _repaid ) internal { loanRepaidOrLiquidated[_loanId] = true; _escrowTokens[_loanTerms.nftCollateralContract][_loanTerms.nftCollateralId] -= 1; _loanCoordinator.resolveLoan(_loanId, _repaid); }
2,861,970
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; 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"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /* Smart Contract for the _____ __ ____ __ _ __ / ___/ __ __ / / ___ ____ ___ _ / __/ __ __ ___ ___/ / (_) ____ ___ _ / /_ ___ ___ / /__ / // / / _ \/ _ \ / __/ / _ `/ _\ \ / // / / _ \/ _ / / / / __// _ `// __// -_) (_-< \___/ \_, / /_.__/\___//_/ \_, / /___/ \_, / /_//_/\_,_/ /_/ \__/ \_,_/ \__/ \__/ /___/ /___/ /___/ /___/ NFT Collection */ contract CyborgSyndicates is ERC721, Ownable, ERC721Enumerable { //Initalising of variables using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; uint256 public earlyBorgPrice = 0.06 ether; uint256 public borgPrice = 0.08 ether; uint256 public maxBorgsPerTx = 10; uint256 public preSaleSupply = 2000; uint256 public maxBorgSupply = 10000; uint256 public saleSupply = 10000; uint256 public maxBorgsInAddress = 10; bool public publicSaleActive = false; bool public preSaleActive = false; string public baseURI = ""; string public prerevealURI = ""; address[] private presaleAddresses; //Whitelisted Addresses //Called on contract deployment constructor() ERC721("Cyborg Syndicates", "BORG") { } /* --------------- Owner Functions --------------- */ //Sends ETH amount from contract to input address - for dev use. function withdrawETH(address _to, uint256 amount) public onlyOwner { require(amount <= address(this).balance, "Amount Requested is too high!"); Address.sendValue(payable(_to), amount); } //Enables/Disables Pre-Sale State. function togglePreSale() public onlyOwner { preSaleActive = !preSaleActive; } //Enables/Disables Main Sale State. function toggleMainSale() public onlyOwner { publicSaleActive = !publicSaleActive; } //Updates borgs presale mint price, only use in the case ETH price fluctuates heavily. function setBorgPrice(uint256 _newBorgPrice) public onlyOwner { borgPrice = _newBorgPrice; } //Updates price of pre-sale borgs mint price, only use in the case ETH price fluctuates heavily. function setEarlyBorgPrice(uint256 _newEarlyBorgPrice) public onlyOwner { earlyBorgPrice = _newEarlyBorgPrice; } //Updates max amount supply for the presale function setPreSaleSupply(uint256 _newPreSaleSupply) public onlyOwner { preSaleSupply = _newPreSaleSupply; } //Updates max amount supply for the sale function setSaleSupply(uint256 _newSaleSupply) public onlyOwner { saleSupply = _newSaleSupply; } //Updates max amount of borgs able to be purchased in 1 transaction. function setMaxBorgsPerTx(uint256 _newMaxBorgsPerTx) public onlyOwner { maxBorgsPerTx = _newMaxBorgsPerTx; } function setMaxBorgsInAddress(uint256 _newMaxBorgsInAddress) public onlyOwner { maxBorgsInAddress = _newMaxBorgsInAddress; } //Updates the baseURI, used for revealing borgs. function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //Updates the prereveal URI, here in case wrong URI is input. function setPreRevealURI(string memory _newPreRevealURI) public onlyOwner { prerevealURI = _newPreRevealURI; } //ERC20 Token recovery if mistakenly sent to contract. function retrieveERC20(address _tracker, uint256 amount) external onlyOwner { IERC20(_tracker).transfer(msg.sender, amount); } //ERC721 Token recovery if mistakenly sent to contract. function retrieve721(address _tracker, uint256 id) external onlyOwner { IERC721(_tracker).transferFrom(address(this), msg.sender, id); } //Adds/Upates list of addresses for addresses whitelisted for presale. function whitelistAddress(address[] calldata _whitelisters) public onlyOwner { presaleAddresses = _whitelisters; } //Adds/Upates list of addresses for addresses whitelisted for presale. function deleteWhitelistAddresses() public onlyOwner { delete presaleAddresses; } /* ----------------- Minting Functions ----------------- */ //Mint reserved Borgs for devs, giveaways, airdrops etc.. function devMint(address _to, uint256 _amount) public onlyOwner { require(totalSupply() + _amount <= maxBorgSupply, "Reserve mint would exceed max Borg limit"); uint256 mintIndex = _tokenIdCounter.current(); for (uint256 i = 1; i <= _amount; i++) { mintIndex++; if(mintIndex <= maxBorgSupply) { _mint(_to, mintIndex); _tokenIdCounter.increment(); } } } //Minting for presale of Borgs function presaleMint(uint256 _amountOfBorgs) public payable { require(preSaleActive, "Presale is not active!"); //Requires presale to be active. require(isAddressWhitelisted(msg.sender), "Address is not whitelisted for presale!"); //Requires msg.sender address to be whitelisted. require(_amountOfBorgs <= maxBorgsPerTx && _amountOfBorgs >= 1, string(abi.encodePacked("Minimum Borgs: 1. Maximum Borgs: ", Strings.toString(maxBorgsPerTx), " per transaction"))); //Requires a value within 1 & max cyborgs per transaction. require(_amountOfBorgs + balanceOf(msg.sender) <= maxBorgsInAddress, string(abi.encodePacked("A maximum of ", Strings.toString(maxBorgsInAddress), " in your wallet. You have ", Strings.toString(balanceOf(msg.sender))))); //Requires the sender to not have more than max Borgs per address. require((totalSupply() + _amountOfBorgs) <= preSaleSupply, "Mint would exceed max supply of the Presale"); //Requires the requested amount to not exceed max supply of Borgs for presale. require(msg.value >= (_amountOfBorgs * earlyBorgPrice), "Not enough ETH sent for the Borgs!"); //Requires the correct amount of ETH sent. uint256 mintIndex = _tokenIdCounter.current(); for (uint256 i = 1; i <= _amountOfBorgs; i++) { mintIndex++; if(mintIndex <= preSaleSupply) { _mint(msg.sender, mintIndex); _tokenIdCounter.increment(); } } } //Minting for main sale of Borgs function publicMint(uint256 _amountOfBorgs) public payable { require(publicSaleActive, "Public sale is not active!"); //Requires public sale to be active. require(_amountOfBorgs + balanceOf(msg.sender) <= maxBorgsInAddress, string(abi.encodePacked("You can have a maximum of ", Strings.toString(maxBorgsInAddress), " per address"))); //Requires the sender address to not have, or be able to have more than max Borgs per address. require(_amountOfBorgs <= maxBorgsPerTx && _amountOfBorgs >= 1, string(abi.encodePacked("Minimum Borgs: 1. Maximum Borgs: ", Strings.toString(maxBorgsPerTx), " per transaction"))); //Requires a value within 1 & max cyborgs per transaction. require(totalSupply() + _amountOfBorgs <= saleSupply, "Mint would exceed max Sale supply!"); //Requires requested amount to not exceed max supply of Borgs. require(msg.value >= (borgPrice * _amountOfBorgs), "Not enough ETH sent!"); //Requires the correct amount of ETH sent. uint256 mintIndex = _tokenIdCounter.current(); for (uint256 i = 1; i <= _amountOfBorgs; i++) { mintIndex++; if(mintIndex <= saleSupply) { _mint(msg.sender, mintIndex); _tokenIdCounter.increment(); } } } /* ---------------------- Public view & Other functions ---------------------- */ function isAddressWhitelisted(address _addressToVerify) public view returns (bool) { if(presaleAddresses.length > 0) { for(uint256 i = 0; i < presaleAddresses.length; i++) { if(presaleAddresses[i] == _addressToVerify) { return true; } } return false; } return false; } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token Does Not Exist"); string memory URISuffix = ".json"; string memory base = baseURI; if(bytes(base).length == 0) { return string(prerevealURI); } else { return string(abi.encodePacked(base, Strings.toString(tokenId), URISuffix)); } } 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); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT 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 "../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 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 "../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: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 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 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; 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; /** * @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); }
Minting for main sale of Borgs
function publicMint(uint256 _amountOfBorgs) public payable { uint256 mintIndex = _tokenIdCounter.current(); for (uint256 i = 1; i <= _amountOfBorgs; i++) { mintIndex++; if(mintIndex <= saleSupply) { _mint(msg.sender, mintIndex); _tokenIdCounter.increment(); } } }
10,258,850
// SPDX-License-Identifier: MIT pragma solidity 0.8.10; import "ERC721Enumerable.sol"; import "SafeMath.sol"; import "Counters.sol"; import "Ownable.sol"; import "Pausable.sol"; import "BPC.sol"; import "BPCSenderRecipient.sol"; import "ExternalFuncs.sol"; contract BPCLottery is ERC721, ERC777SenderRecipientMock, Ownable, Pausable { //using ExternalFuncs for *; using Counters for Counters.Counter; using SafeMath for uint256; IERC777 private m_bpc; bool private m_bpc_is_set; modifier isTokenSet() { require(m_bpc_is_set, "ERC777 is not set"); _; } address private m_company_account; Counters.Counter private m_ticket_id; Counters.Counter private m_lottery_id; uint256 private m_ticket_price; bool private is_lottery_open; uint256 private constant m_duration = 7 days; struct Winner { uint256 ticket_id; address addr; bool isSet; } mapping(uint256 => uint256) private m_lottery_id_pot; mapping(uint256 => uint256) private m_lottery_id_expires_at; mapping(uint256 => bool) private m_lottery_id_paid; mapping(uint256 => Winner) private m_lottery_id_winner; event WinnerAnnounced( address winner, uint256 winner_id, uint256 lottery_id, uint256 prize_size ); event WinnerPaid(address winner, uint256 lottery_id, uint256 prize_size); constructor( string memory _name, string memory _symbol, uint256 _ticket_price, address _company_account ) ERC721(_name, _symbol) { m_company_account = _company_account; // ERC-777 receiver init // See https://forum.openzeppelin.com/t/simple-erc777-token-example/746 _erc1820.setInterfaceImplementer( address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this) ); m_ticket_price = _ticket_price != 0 ? _ticket_price : 5000000000000000000; // 5 * 10^18 m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add( m_duration ); m_lottery_id_paid[m_lottery_id.current()] = false; is_lottery_open = true; m_bpc_is_set = false; } function setERC777(address _bpc) public onlyOwner { require(_bpc != address(0), "BPC address cannot be 0"); require( !m_bpc_is_set, "You have already set BPC address, can't do it again" ); m_bpc = IERC777(_bpc); m_bpc_is_set = true; } function pause() public onlyOwner whenNotPaused { _pause(); } function unPause() public onlyOwner whenPaused { _unpause(); } //function paused() public view comes as a base class method of Pausable function setTicketPrice(uint256 new_ticket_price) public onlyOwner isTokenSet { require(new_ticket_price > 0, "Ticket price should be greater than 0"); m_ticket_price = new_ticket_price; } //when not paused function getTicketPrice() public view returns (uint256) { require(!paused(), "Lottery is paused, please come back later"); return m_ticket_price; } //when not paused function buyTicket(uint256 bpc_tokens_amount, address participant) public isTokenSet { require(!paused(), "Lottery is paused, please come back later"); require( m_bpc.isOperatorFor(msg.sender, participant), "You MUST be an operator for participant" ); require( bpc_tokens_amount.mod(m_ticket_price) == 0, "Tokens amount should be a multiple of a Ticket Price" ); require( m_bpc.balanceOf(participant) >= bpc_tokens_amount, "You should have enough of Tokens in your Wallet" ); m_bpc.operatorSend( participant, address(this), bpc_tokens_amount, bytes(""), bytes("") ); m_lottery_id_pot[m_lottery_id.current()] = m_lottery_id_pot[ m_lottery_id.current() ].add(bpc_tokens_amount); uint256 tickets_count = bpc_tokens_amount.div(m_ticket_price); for (uint256 i = 0; i != tickets_count; ++i) { m_ticket_id.increment(); _mint(participant, m_ticket_id.current()); } } //when not paused function getCurrentLotteryTicketsCount(address participant) public view returns (uint256) { require(!paused(), "Lottery is paused, please come back later"); require( m_bpc.isOperatorFor(msg.sender, participant), "You MUST be an operator for participant" ); return this.balanceOf(participant); } function getCurrentLotteryId() public view returns (uint256) { return m_lottery_id.current(); } function getCurrentLotteryPot() public view returns (uint256) { return m_lottery_id_pot[m_lottery_id.current()]; } function announceWinnerAndRevolve() public onlyOwner isTokenSet { require(isLotteryPeriodOver(), "The current lottery is still running"); forceAnnounceWinnerAndRevolve(); } function forceAnnounceWinnerAndRevolve() public onlyOwner isTokenSet { uint256 prize_size = m_lottery_id_pot[m_lottery_id.current()].div(2); uint256 id = m_lottery_id.current(); if (!m_lottery_id_winner[id].isSet) { m_lottery_id_winner[id] = setWinner(prize_size); } if (!isEmptyWinner(m_lottery_id_winner[id]) && !m_lottery_id_paid[id]) { splitPotWith(m_lottery_id_winner[id].addr, prize_size); m_lottery_id_paid[id] = true; m_lottery_id_pot[id] = 0; } if (!paused()) { revolveLottery(); } } function isLotteryPeriodOver() private view returns (bool) { return m_lottery_id_expires_at[m_lottery_id.current()] < block.timestamp; } function getWinner(uint256 id) public view returns (address) { require( m_lottery_id_winner[id].isSet, "Lottery Id Winner or Lottery Id not found" ); return m_lottery_id_winner[id].addr; } function setWinner(uint256 prize_size) private returns (Winner memory) { Winner memory winner; winner.isSet = true; if (m_ticket_id.current() != 0) { winner.ticket_id = prng().mod(m_ticket_id.current()).add(1); winner.addr = this.ownerOf(winner.ticket_id); emit WinnerAnnounced( winner.addr, winner.ticket_id, m_lottery_id.current(), prize_size ); } else { winner.ticket_id = 0; winner.addr = address(0); } return winner; } function isEmptyWinner(Winner memory winner) private pure returns (bool) { return winner.addr == address(0); } function splitPotWith(address winner_address, uint256 prize_size) private { m_bpc.operatorSend( address(this), winner_address, prize_size, bytes(""), bytes("") ); m_bpc.operatorSend( address(this), m_company_account, prize_size, bytes(""), bytes("") ); emit WinnerPaid(winner_address, m_lottery_id.current(), prize_size); } function revolveLottery() private { uint256 size = m_ticket_id.current(); if (size != 0) { for (uint256 i = 1; i <= size; ++i) { _burn(i); } } m_ticket_id.reset(); m_lottery_id.increment(); m_lottery_id_expires_at[m_lottery_id.current()] = block.timestamp.add( m_duration ); } function prng() private view returns (uint256) { return uint256( keccak256( abi.encodePacked( block.difficulty, block.timestamp, m_ticket_id.current() ) ) ); } } // 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 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "IERC721.sol"; import "IERC721Receiver.sol"; import "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "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); } /** * @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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "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 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // 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 (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 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: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.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. */ 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 "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.10; import "ERC777.sol"; import "AccessControl.sol"; import "SafeMath.sol"; import "ReentrancyGuard.sol"; contract BPC is ERC777, AccessControl, ReentrancyGuard { using SafeMath for uint256; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private constant m_tokens_per_eth = 100; address private m_company_account; uint256 private m_entry_fee; uint256 private m_exit_fee; uint256 private m_max_supply; constructor( string memory _name, string memory _symbol, address[] memory _default_operators, uint256 _max_supply, uint256 _initial_supply, uint256 _entry_fee, uint256 _exit_fee, address _managing_account, address _company_account ) ERC777(_name, _symbol, _default_operators) { _grantRole(DEFAULT_ADMIN_ROLE, _managing_account); _grantRole(MINTER_ROLE, _company_account); m_max_supply = _max_supply; _mint(_company_account, _initial_supply, "", "", false); m_company_account = _company_account; m_entry_fee = _entry_fee; m_exit_fee = _exit_fee; } function mint(uint256 amount) public onlyRole(MINTER_ROLE) { require( totalSupply().add(amount) <= m_max_supply, "Amount that is about to be minted reaches the Max Supply" ); _mint(msg.sender, amount, bytes(""), bytes(""), false); } //burn and operatorBurn of ERC777 make all required checks and update _totalSupply that holds current Tokens qty //no need to override those funcs function fromEtherToTokens() public payable { uint256 tokens_to_buy = msg.value * m_tokens_per_eth; uint256 company_token_balance = this.balanceOf(m_company_account); require( tokens_to_buy > 0, "You need to send some more ether, what you provide is not enough for transaction" ); require( tokens_to_buy <= company_token_balance, "Not enough tokens in the reserve" ); uint256 updated_value = getEntryFeeValue(tokens_to_buy); _send( m_company_account, msg.sender, updated_value, bytes(""), bytes(""), false ); } function fromTokensToEther(uint256 tokens_to_sell) public nonReentrant { require(tokens_to_sell > 0, "You need to sell at least some tokens"); // Check that the user's token balance is enough to do the swap uint256 user_token_balance = this.balanceOf(msg.sender); require( user_token_balance >= tokens_to_sell, "Your balance is lower than the amount of tokens you want to sell" ); uint256 updated_value = getExitFeeValue(tokens_to_sell); uint256 eth_to_transfer = updated_value / m_tokens_per_eth; uint256 company_eth_balance = address(this).balance; require( company_eth_balance >= eth_to_transfer, "BPC Owner doesn't have enough funds to accept this sell request" ); _send( msg.sender, m_company_account, tokens_to_sell, bytes(""), bytes(""), false ); payable(msg.sender).transfer(eth_to_transfer); } function getTokenPrice() public view returns (uint256) { return m_tokens_per_eth; } function getEntryFee() public view returns (uint256) { return m_entry_fee; } function getExitFee() public view returns (uint256) { return m_exit_fee; } function setEntryFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) { require( fee >= 0 && fee <= 100, "Fee must be an integer percentage, ie 42" ); m_entry_fee = fee; } function setExitFee(uint256 fee) public onlyRole(DEFAULT_ADMIN_ROLE) { require( fee >= 0 && fee <= 100, "Fee must be an integer percentage, ie 42" ); m_exit_fee = fee; } function getEntryFeeValue(uint256 value) private view returns (uint256) { if (m_entry_fee != 0) { uint256 fee_value = (m_entry_fee * value) / 100; uint256 updated_value = value - fee_value; return updated_value; } else { return value; } } function getExitFeeValue(uint256 value) private view returns (uint256) { if (m_exit_fee != 0) { uint256 fee_value = (m_exit_fee * value) / 100; uint256 updated_value = value - fee_value; return updated_value; } else { return value; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/ERC777.sol) pragma solidity ^0.8.0; import "IERC777.sol"; import "IERC777Recipient.sol"; import "IERC777Sender.sol"; import "IERC20.sol"; import "Address.sol"; import "Context.sol"; import "IERC1820Registry.sol"; /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using Address for address; IERC1820Registry internal constant _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; bytes32 private constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 private constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping(address => mapping(address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name_, string memory symbol_, address[] memory defaultOperators_ ) { _name = name_; _symbol = symbol_; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < defaultOperators_.length; i++) { _defaultOperators[defaultOperators_[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure virtual returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view virtual override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send( address recipient, uint256 amount, bytes memory data ) public virtual override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public virtual override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn( address account, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom( address holder, address recipient, uint256 amount ) public virtual override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); uint256 currentAllowance = _allowances[holder][spender]; require(currentAllowance >= amount, "ERC777: transfer amount exceeds allowance"); _approve(holder, spender, currentAllowance - amount); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { _mint(account, amount, userData, operatorData, true); } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If `requireReceptionAck` is set to true, and if a send hook is * registered for `account`, the corresponding function will be called with * `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply += amount; _balances[account] += amount; _callTokensReceived(operator, address(0), account, amount, userData, operatorData, requireReceptionAck); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); // Update state variables uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: burn amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _totalSupply -= amount; emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC777: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve( address holder, address spender, uint256 value ) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send( address recipient, uint256 amount, bytes calldata data ) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Sender.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // 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: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol) pragma solidity ^0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer( address account, bytes32 _interfaceHash, address implementer ) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "IAccessControl.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "IERC777.sol"; import "IERC777Sender.sol"; import "IERC777Recipient.sol"; import "Context.sol"; import "IERC1820Registry.sol"; import "ERC1820Implementer.sol"; contract ERC777SenderRecipientMock is Context, IERC777Sender, IERC777Recipient, ERC1820Implementer { event TokensToSendCalled( address operator, address from, address to, uint256 amount, bytes data, bytes operatorData, address token, uint256 fromBalance, uint256 toBalance ); event TokensReceivedCalled( address operator, address from, address to, uint256 amount, bytes data, bytes operatorData, address token, uint256 fromBalance, uint256 toBalance ); // Emitted in ERC777Mock. Here for easier decoding event BeforeTokenTransfer(); bool private _shouldRevertSend; bool private _shouldRevertReceive; IERC1820Registry public _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 public constant _TOKENS_SENDER_INTERFACE_HASH = keccak256("ERC777TokensSender"); bytes32 public constant _TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { if (_shouldRevertSend) { revert(); } IERC777 token = IERC777(_msgSender()); uint256 fromBalance = token.balanceOf(from); // when called due to burn, to will be the zero address, which will have a balance of 0 uint256 toBalance = token.balanceOf(to); emit TokensToSendCalled( operator, from, to, amount, userData, operatorData, address(token), fromBalance, toBalance ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override { if (_shouldRevertReceive) { revert(); } IERC777 token = IERC777(_msgSender()); uint256 fromBalance = token.balanceOf(from); // when called due to burn, to will be the zero address, which will have a balance of 0 uint256 toBalance = token.balanceOf(to); emit TokensReceivedCalled( operator, from, to, amount, userData, operatorData, address(token), fromBalance, toBalance ); } function senderFor(address account) public { _registerInterfaceForAddress(_TOKENS_SENDER_INTERFACE_HASH, account); address self = address(this); if (account == self) { registerSender(self); } } function registerSender(address sender) public { _erc1820.setInterfaceImplementer(address(this), _TOKENS_SENDER_INTERFACE_HASH, sender); } function recipientFor(address account) public { _registerInterfaceForAddress(_TOKENS_RECIPIENT_INTERFACE_HASH, account); address self = address(this); if (account == self) { registerRecipient(self); } } function registerRecipient(address recipient) public { _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, recipient); } function setShouldRevertSend(bool shouldRevert) public { _shouldRevertSend = shouldRevert; } function setShouldRevertReceive(bool shouldRevert) public { _shouldRevertReceive = shouldRevert; } function send( IERC777 token, address to, uint256 amount, bytes memory data ) public { // This is 777's send function, not the Solidity send function token.send(to, amount, data); // solhint-disable-line check-send-result } function burn( IERC777 token, uint256 amount, bytes memory data ) public { token.burn(amount, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol) pragma solidity ^0.8.0; import "IERC1820Implementer.sol"; /** * @dev Implementation of the {IERC1820Implementer} interface. * * Contracts may inherit from this and call {_registerInterfaceForAddress} to * declare their willingness to be implementers. * {IERC1820Registry-setInterfaceImplementer} should then be called for the * registration to be complete. */ contract ERC1820Implementer is IERC1820Implementer { bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC"); mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces; /** * @dev See {IERC1820Implementer-canImplementInterfaceForAddress}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) public view virtual override returns (bytes32) { return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00); } /** * @dev Declares the contract as willing to be an implementer of * `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer} and * {IERC1820Registry-interfaceHash}. */ function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual { _supportedInterfaces[interfaceHash][account] = true; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol) pragma solidity ^0.8.0; /** * @dev Interface for an ERC1820 implementer, as defined in the * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP]. * Used by contracts that will be registered as implementers in the * {IERC1820Registry}. */ interface IERC1820Implementer { /** * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract * implements `interfaceHash` for `account`. * * See {IERC1820Registry-setInterfaceImplementer}. */ function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "ABDKMath64x64.sol"; import "Strings.sol"; library ExternalFuncs { // from here https://medium.com/coinmonks/math-in-solidity-part-4-compound-interest-512d9e13041b /* function pow (int128 x, uint n) public pure returns (int128 r) { r = ABDKMath64x64.fromUInt (1); while (n > 0) { if (n % 2 == 1) { r = ABDKMath64x64.mul (r, x); n -= 1; } else { x = ABDKMath64x64.mul (x, x); n /= 2; } } } */ function compound( uint256 principal, uint256 ratio, uint256 n ) public pure returns (uint256) { return ABDKMath64x64.mulu( ABDKMath64x64.pow( //pow - original code ABDKMath64x64.add( ABDKMath64x64.fromUInt(1), ABDKMath64x64.divu(ratio, 10**4) ), //(1+r), where r is allowed to be one hundredth of a percent, ie 5/100/100 n ), //(1+r)^n principal ); //A_0 * (1+r)^n } function Today() public view returns (uint256) { return block.timestamp / 1 days; } function isStakeSizeOk(uint256 amount, uint256 decimals) public pure returns (bool) { return amount == 1000 * 10**decimals || amount == 3000 * 10**decimals || amount == 5000 * 10**decimals || amount == 10000 * 10**decimals || amount == 20000 * 10**decimals || amount == 50000 * 10**decimals || amount == 100000 * 10**decimals || amount == 250000 * 10**decimals || amount >= 1000000 * 10**decimals; } function getErrorMsg(string memory text, uint256 value) public pure returns (string memory) { string memory _msg = string( abi.encodePacked(text, Strings.toString(value)) ); return _msg; } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { unchecked { 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) { unchecked { 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) { unchecked { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(int256(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) { unchecked { require(x >= 0); return uint64(uint128(x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128(int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128(int128 x) internal pure returns (int256) { unchecked { return int256(x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { unchecked { 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) { unchecked { 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) { unchecked { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli(int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require( y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000 ); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu(x, uint256(y)); if (negativeResult) { require( absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000 ); return -int256(absoluteResult); // We rely on overflow behavior here } else { require( absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); return int256(absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require(x >= 0); uint256 lo = (uint256(int256(x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256(int256(x)) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div(int128 x, int128 y) internal pure returns (int128) { unchecked { require(y != 0); int256 result = (int256(x) << 64) / y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi(int256 x, int256 y) internal pure returns (int128) { unchecked { require(y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu(uint256(x), uint256(y)); if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { unchecked { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg(int128 x) internal pure returns (int128) { unchecked { require(x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs(int128 x) internal pure returns (int128) { unchecked { require(x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { unchecked { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg(int128 x, int128 y) internal pure returns (int128) { unchecked { return int128((int256(x) + int256(y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg(int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256(x) * int256(y); require(m >= 0); require( m < 0x4000000000000000000000000000000000000000000000000000000000000000 ); return int128(sqrtu(uint256(m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128(x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x2 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x4 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; if (y & 0x8 != 0) { absResult = (absResult * absX) >> 127; } absX = (absX * absX) >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require(absXShift < 64); if (y & 0x1 != 0) { absResult = (absResult * absX) >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = (absX * absX) >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require(resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256(absResult) : int256(absResult); require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt(int128 x) internal pure returns (int128) { unchecked { require(x >= 0); return int128(sqrtu(uint256(int256(x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { unchecked { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(int256(x)) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { unchecked { require(x > 0); return int128( int256( (uint256(int256(log_2(x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ) ); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2(int128 x) internal pure returns (int128) { unchecked { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128; if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128; if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128; if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128; if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128; if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128; if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128; result >>= uint256(int256(63 - (x >> 64))); require(result <= uint256(int256(MAX_64x64))); return int128(int256(result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp(int128 x) internal pure returns (int128) { unchecked { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2( int128( (int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128 ) ); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) private pure returns (uint128) { unchecked { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { unchecked { 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); } } } }
Calculate x - y. Revert on overflow. x signed 64.64-bit fixed point number 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) { unchecked { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } }
154,142
// SPDX-License-Identifier: MIT /// @title Timelock for ERC721Governor. pragma solidity ^0.8.6; import { TimelockControllerUpgradeable } from "@openzeppelin/contracts-upgradeable/governance/TimelockControllerUpgradeable.sol"; import { UUPSUpgradeable } from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol"; import { ERC721HolderUpgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; contract ERC721Timelock is TimelockControllerUpgradeable, UUPSUpgradeable, ERC721HolderUpgradeable { function initialize( uint256 minDelay, address[] memory proposers, address[] memory executors ) public initializer { __TimelockController_init(minDelay, proposers, executors); // __TimelockController_init sets _msgSender as admin as well as the timelock itself. // We don't want the clone creating contract to remain the admin of the timelocks it // creates. revokeRole(TIMELOCK_ADMIN_ROLE, _msgSender()); } function _authorizeUpgrade(address) internal override onlyRole(TIMELOCK_ADMIN_ROLE) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/TimelockController.sol) pragma solidity ^0.8.0; import "../access/AccessControlUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockControllerUpgradeable is Initializable, AccessControlUpgradeable { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`. */ function __TimelockController_init( uint256 minDelay, address[] memory proposers, address[] memory executors ) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __TimelockController_init_unchained(minDelay, proposers, executors); } function __TimelockController_init_unchained( uint256 minDelay, address[] memory proposers, address[] memory executors ) internal onlyInitializing { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ function execute( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(id, predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { require(isOperationReady(id), "TimelockController: operation is not ready"); require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call( bytes32 id, uint256 index, address target, uint256 value, bytes calldata data ) private { (bool success, ) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } uint256[48] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../../interfaces/draft-IERC1822.sol"; import "../ERC1967/ERC1967Upgrade.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 IERC1822Proxiable, ERC1967Upgrade { /// @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; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal onlyInitializing { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal onlyInitializing { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.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 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 { __Context_init_unchained(); } 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; } 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 StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library 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/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.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 IERC1822Proxiable { /** * @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-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.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 ERC1967Upgrade { // 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.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) { Address.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 (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(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 StorageSlot.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"); StorageSlot.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 StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.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) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // 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 IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts 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 StorageSlot { 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 v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
deployer + self administration register proposers register executors
function __TimelockController_init_unchained( uint256 minDelay, address[] memory proposers, address[] memory executors ) internal onlyInitializing { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); }
1,691,006
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by requiring a state. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier inNormalState { assert(!halted); _; } modifier inEmergencyState { assert(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner inNormalState { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner inEmergencyState { halted = false; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Burnable * * @dev Standard ERC20 token */ contract Burnable is StandardToken { using SafeMath for uint; /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); function burn(uint256 _value) returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value);// Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns (bool success) { require(balances[_from] >= _value); // Check if the sender has enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Burn(_from, _value); return true; } function transfer(address _to, uint _value) returns (bool success) { require(_to != 0x0); //use burn return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) returns (bool success) { require(_to != 0x0); //use burn return super.transferFrom(_from, _to, _value); } } /** * @title JincorToken * * @dev Burnable Ownable ERC20 token */ contract JincorToken is Burnable, Ownable { string public name = "Jincor Token"; string public symbol = "JCR"; uint256 public decimals = 18; uint256 public INITIAL_SUPPLY = 35000000 * 1 ether; /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** * Limit token transfer until the crowdsale is over. * */ modifier canTransfer(address _sender) { require(transferAgents[_sender] || released); _; } /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { require(releaseState == released); _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { require(msg.sender == releaseAgent); _; } /** * @dev Contructor that gives msg.sender all of existing tokens. */ function JincorToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don&#39;t do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } function release() onlyReleaseAgent inReleaseState(false) public { released = true; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) { // Call Burnable.transfer() return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) { // Call Burnable.transferForm() return super.transferFrom(_from, _to, _value); } function burn(uint256 _value) onlyOwner returns (bool success) { return super.burn(_value); } function burnFrom(address _from, uint256 _value) onlyOwner returns (bool success) { return super.burnFrom(_from, _value); } } contract JincorTokenPreSale is Ownable, Haltable { using SafeMath for uint; string public name = "Jincor Token PreSale"; JincorToken public token; address public beneficiary; uint public hardCap; uint public softCap; uint public price; uint public purchaseLimit; uint public collected = 0; uint public tokensSold = 0; uint public investorCount = 0; uint public weiRefunded = 0; uint public startBlock; uint public endBlock; bool public softCapReached = false; bool public crowdsaleFinished = false; mapping (address => bool) refunded; event GoalReached(uint amountRaised); event SoftCapReached(uint softCap); event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount); event Refunded(address indexed holder, uint256 amount); modifier preSaleActive() { require(block.number >= startBlock && block.number < endBlock); _; } modifier preSaleEnded() { require(block.number >= endBlock); _; } function JincorTokenPreSale( uint _hardCapUSD, uint _softCapUSD, address _token, address _beneficiary, uint _totalTokens, uint _priceETH, uint _purchaseLimitUSD, uint _startBlock, uint _endBlock ) { hardCap = _hardCapUSD.mul(1 ether).div(_priceETH); softCap = _softCapUSD.mul(1 ether).div(_priceETH); price = _totalTokens.mul(1 ether).div(hardCap); purchaseLimit = _purchaseLimitUSD.mul(1 ether).div(_priceETH).mul(price); token = JincorToken(_token); beneficiary = _beneficiary; startBlock = _startBlock; endBlock = _endBlock; } function() payable { require(msg.value >= 0.1 * 1 ether); doPurchase(msg.sender); } function refund() external preSaleEnded inNormalState { require(softCapReached == false); require(refunded[msg.sender] == false); uint balance = token.balanceOf(msg.sender); require(balance > 0); uint refund = balance.div(price); if (refund > this.balance) { refund = this.balance; } assert(msg.sender.send(refund)); refunded[msg.sender] = true; weiRefunded = weiRefunded.add(refund); Refunded(msg.sender, refund); } function withdraw() onlyOwner { require(softCapReached); assert(beneficiary.send(collected)); token.transfer(beneficiary, token.balanceOf(this)); crowdsaleFinished = true; } function doPurchase(address _owner) private preSaleActive inNormalState { require(!crowdsaleFinished); require(collected.add(msg.value) <= hardCap); if (!softCapReached && collected < softCap && collected.add(msg.value) >= softCap) { softCapReached = true; SoftCapReached(softCap); } uint tokens = msg.value * price; require(token.balanceOf(msg.sender).add(tokens) <= purchaseLimit); if (token.balanceOf(msg.sender) == 0) investorCount++; collected = collected.add(msg.value); token.transfer(msg.sender, tokens); tokensSold = tokensSold.add(tokens); NewContribution(_owner, tokens, msg.value); if (collected == hardCap) { GoalReached(hardCap); } } }
Set the contract that can call release and make the token transferable. Design choice. Allow reset the release agent to fix fat finger mistakes./ We don&39;t do interface check here as we might want to a normal wallet address to act as a release agent
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { releaseAgent = addr; }
15,313,862
/** *Submitted for verification at Etherscan.io on 2021-03-23 */ /** *Submitted for verification at Etherscan.io on 2021-03-19 */ // File: zos-lib/contracts/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @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 is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function initialize(address sender) public initializer { _owner = sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } // File: openzeppelin-eth/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also SATOed. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/lib/SafeMathInt.sol /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 SATO, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.4.24; /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } // File: contracts/lib/UInt256Lib.sol pragma solidity 0.4.24; /** * @title Various utilities useful for uint256. */ library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); /** * @dev Safely converts a uint256 to an int256. */ function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } // File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.4.24; /** * @title ERC20Detailed token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } // File: contracts/SATO.sol pragma solidity 0.4.24; /** * @title SATO ERC20 token * @dev This is part of an implementation of the SATO Ideal Money protocol. * SATO is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */ contract SATO is ERC20Detailed, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into SATO are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x SATO to address 'B'. A's resulting external balance will // be decreased by precisely x SATO, and B's external balance will be precisely // increased by x SATO. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogRebasePaused(bool paused); event LogTokenPaused(bool paused); event LogSATOPolicyUpdated(address SATOPolicy); // Used for authentication address public SATOPolicy; modifier onlySATOPolicy() { require(msg.sender == SATOPolicy); _; } // Precautionary emergency controls. bool public rebasePaused; bool public tokenPaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } modifier whenTokenNotPaused() { require(!tokenPaused); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_SATO_SUPPLY = 5000000 * 10**DECIMALS; // TOTAL_GONS is a multiple of INITIAL_SATO_SUPPLY so that _gonsPerFragment is an integer. // Use the highest value that fits in a uint256 for max granularity. uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_SATO_SUPPLY); // MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2 uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _gonsPerFragment; mapping(address => uint256) private _gonBalances; // This is denominated in SATO, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedSATO; /** * @param SATOPolicy_ The address of the SATO policy contract to use for authentication. */ function setSATOPolicy(address SATOPolicy_) external onlyOwner { SATOPolicy = SATOPolicy_; emit LogSATOPolicyUpdated(SATOPolicy_); } /** * @dev Pauses or unpauses the execution of rebase operations. * @param paused Pauses rebase operations if this is true. */ function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } /** * @dev Pauses or unpauses execution of ERC-20 transactions. * @param paused Pauses ERC-20 transactions if this is true. */ function setTokenPaused(bool paused) external onlyOwner { tokenPaused = paused; emit LogTokenPaused(paused); } /** * @dev Notifies SATO contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external onlySATOPolicy whenRebaseNotPaused returns (uint256) { if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } _gonsPerFragment = TOTAL_GONS.div(_totalSupply); // From this point forward, _gonsPerFragment is taken as the source of truth. // We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment // conversion rate. // This means our applied supplyDelta can deviate from the requested supplyDelta, // but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply). // // In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this // deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is // ever increased, it must be re-included. // _totalSupply = TOTAL_GONS.div(_gonsPerFragment) emit LogRebase(epoch, _totalSupply); return _totalSupply; } function initialize(address owner_) public initializer { ERC20Detailed.initialize("SwapAll Algorithmic Token", "SATO", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; tokenPaused = false; _totalSupply = INITIAL_SATO_SUPPLY; _gonBalances[owner_] = TOTAL_GONS; _gonsPerFragment = TOTAL_GONS.div(_totalSupply); emit Transfer(address(0x0), owner_, _totalSupply); } /** * @return The total number of fragments. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view returns (uint256) { return _gonBalances[who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public validRecipient(to) whenTokenNotPaused returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(msg.sender, to, value); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view returns (uint256) { return _allowedSATO[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) whenTokenNotPaused returns (bool) { _allowedSATO[from][msg.sender] = _allowedSATO[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public whenTokenNotPaused returns (bool) { _allowedSATO[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public whenTokenNotPaused returns (bool) { _allowedSATO[msg.sender][spender] = _allowedSATO[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedSATO[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenTokenNotPaused returns (bool) { uint256 oldValue = _allowedSATO[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedSATO[msg.sender][spender] = 0; } else { _allowedSATO[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedSATO[msg.sender][spender]); return true; } } // File: contracts/SATOPolicy.sol pragma solidity 0.4.24; interface IOracle { function getData() external returns (uint256, bool); } /** * @title SATO Monetary Supply Policy * @dev This is an implementation of the SATO Ideal Money protocol. * SATO operates symmetrically on expansion and contraction. It will both split and * combine coins to maintain a stable unit price. * * This component regulates the token supply of the SATO ERC20 token in response to * market oracles. */ contract SATOPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); SATO public uFrags; // Provides the current CPI, as an 18 decimal fixed point number. IOracle public cpiOracle; // Market oracle provides the token/USD exchange rate as an 18 decimal fixed point number. // (eg) An oracle value of 1.5e18 it would mean 1 RAM is trading for $1.50. IOracle public marketOracle; // CPI value at the time of launch, as an 18 decimal fixed point number. uint256 private baseCpi; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. // DECIMALS Fixed point number. uint256 public deviationThreshold; // The rebase lag parameter, used to dampen the applied supply adjustment by 1 / rebaseLag // Check setRebaseLag comments for more details. // Natural number, no decimal places. uint256 public rebaseLag; // More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; // Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; // The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; // The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; // The number of rebase cycles since inception uint256 public epoch; uint256 private constant DECIMALS = 18; // Due to the expression in computeSupplyDelta(), MAX_RATE * MAX_SUPPLY must fit into an int256. // Both are 18 decimals fixed point numbers. uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; // MAX_SUPPLY = MAX_INT256 / MAX_RATE uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; // This module orchestrates the rebase execution and downstream notification. address public orchestrator; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase() external onlyOrchestrator { require(inRebaseWindow()); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); uint256 cpi; bool cpiValid; (cpi, cpiValid) = cpiOracle.getData(); require(cpiValid); uint256 targetRate = cpi.mul(10 ** DECIMALS).div(baseCpi); uint256 exchangeRate; bool rateValid; (exchangeRate, rateValid) = marketOracle.getData(); require(rateValid); if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, cpi, supplyDelta, now); } /** * @notice Emergency rebase by owner. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1 */ function EmergencyRebase(uint256 _price) external onlyOrchestrator { epoch = epoch.add(1); uint256 targetRate = 1; uint256 exchangeRate = _price; if (exchangeRate > MAX_RATE) { exchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(exchangeRate, targetRate); // Apply the Dampening factor. supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe()); if (supplyDelta > 0 && uFrags.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(uFrags.totalSupply())).toInt256Safe(); } uint256 supplyAfterRebase = uFrags.rebase(epoch, supplyDelta); assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, exchangeRate, _price, supplyDelta, now); } /** * @notice Sets the reference to the CPI oracle. * @param cpiOracle_ The address of the cpi oracle contract. */ function setCpiOracle(IOracle cpiOracle_) external onlyOwner { cpiOracle = cpiOracle_; } /** * @notice Sets the reference to the market oracle. * @param marketOracle_ The address of the market oracle contract. */ function setMarketOracle(IOracle marketOracle_) external onlyOwner { marketOracle = marketOracle_; } /** * @notice Sets the reference to the orchestrator. * @param orchestrator_ The address of the orchestrator contract. */ function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. DECIMALS fixed point number. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @dev ZOS upgradable contract initialization method. * It is called at the time of contract creation to invoke parent class initializers and * initialize the contract's state variables. */ function initialize(address owner_, SATO uFrags_, uint256 baseCpi_) public initializer { Ownable.initialize(owner_); // deviationThreshold = 0.05e18 = 5e16 deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 30; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 72000; // 8PM UTC rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; epoch = 0; uFrags = uFrags_; baseCpi = baseCpi_; } /** * @return If the laSATO block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } /** * @return Computes the total supply adjustment in response to the exchange rate * and the targetRate. */ function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } // supplyDelta = totalSupply * (rate - targetRate) / targetRate int256 targetRateSigned = targetRate.toInt256Safe(); return uFrags.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @param targetRate The target exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } // File: contracts/Orchestrator.sol pragma solidity 0.4.24; /** * @title Orchestrator * @notice The orchestrator is the main entry point for rebase operations. It coordinates the policy * actions with external consumers. */ contract Orchestrator is Ownable { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); // Stable ordering is not guaranteed. Transaction[] public transactions; SATOPolicy public policy; mapping(address => bool) public isAdmin; /** * @param policy_ Address of the SATO policy. */ constructor(address policy_) public { Ownable.initialize(msg.sender); policy = SATOPolicy(policy_); } function addAdmin(address _admin) external onlyOwner { isAdmin[_admin] = true; } /** * @notice Main entry point to initiate a rebase operation. * The Orchestrator calls rebase on the policy and notifies downstream applications. * Contracts are guarded from calling, to avoid flash loan attacks on liquidity * providers. * If a transaction in the transaction list reverts, it is swallowed and the remaining * transactions are executed. */ function rebase() external onlyAdmin { require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin policy.rebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } // Emergency Rebase function EmergencyRebase(uint256 _price) external onlyAdmin { policy.EmergencyRebase(_price); } /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @return Number of transactions, both enabled and disabled, in transactions list. */ function transactionsSize() external view returns (uint256) { return transactions.length; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } modifier onlyAdmin() { require(isAdmin[msg.sender] == true, "only admin can call rebase method"); _; } }
Transfer tokens from one address to another. from The address you want to send tokens from. to The address you want to transfer to. value The amount of tokens to be transferred./
function transferFrom(address from, address to, uint256 value) public validRecipient(to) whenTokenNotPaused returns (bool) { _allowedSATO[from][msg.sender] = _allowedSATO[from][msg.sender].sub(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[from] = _gonBalances[from].sub(gonValue); _gonBalances[to] = _gonBalances[to].add(gonValue); emit Transfer(from, to, value); return true; }
2,419,846
./full_match/1/0x622a1C6a0f49594f6BA11F0B8cE8706F1f14cc8d/sources/contracts/TicketStorage.sol
Returns total amount of tickets./
function getTickets() public view returns (uint16) { return _tickets; }
8,321,547
./partial_match/1/0x067C5714f9c034fda974f909591c75A710C8f6eb/sources/MULTINFT_METAVERSE_NIGHTS.sol
Returns the number of tokens burned by or on behalf of `owner`./
function numberBurned(address owner, uint256 tokenId) public view returns (uint256) { return (_packedAddressData[owner][tokenId] >> _BITPOS_NUMBER_BURNED) & _BITMASK_DATA_ENTRY; }
9,130,748
./partial_match/1/0x48b95265749775310B77418Ff6f9675396ABE1e8/sources/@yield-protocol/yieldspace-tv/src/YieldMath.sol
Calculates the max amount of fyToken a user could sell. sharesReserves yield bearing vault shares reserve amount fyTokenReserves fyToken reserves amount timeTillMaturity time till maturity in seconds e.g. 90 days in seconds k time till maturity coefficient, multiplied by 2^64. e.g. 25 years in seconds g fee coefficient, multiplied by 2^64 -- sb over 1.0 for buying shares from the pool c price of shares in terms of their base, multiplied by 2^64 return fyTokenIn the max amount of fyToken a user could sell normalizedSharesReserves = μ sharesReserves za = c/μ (normalizedSharesReserves a) The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) (2^63)^(1 - y/z) ya = fyTokenReserves a The “pow(x, y, z)” function not only calculates x^(y/z) but also normalizes the result to fit into 64.64 fixed point number, i.e. it actually calculates: x^(y/z) (2^63)^(1 - y/z) sum = za + ya z < MAX, y < MAX, a < 1. It can only underflow, not overflow.
function maxFYTokenIn( uint128 sharesReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 k, int128 g, int128 c, int128 mu ) public pure returns (uint128 fyTokenIn) { Y = fyToken reserves Z = shares reserves y = maxFYTokenIn ( sum )^( invA ) - Y ( Za ) + ( Ya ) )^( invA ) - Y Δy = ( c/μ * (μz)^(1-t) + Y^(1-t) )^(1 / (1 - t)) - Y */ unchecked { require(c > 0 && mu > 0, "YieldMath: c and mu must be positive"); uint128 a = _computeA(timeTillMaturity, k, g); uint256 sum; { uint256 normalizedSharesReserves; require((normalizedSharesReserves = mu.mulu(sharesReserves)) <= MAX, "YieldMath: Rate overflow (nsr)"); uint256 za; require( (za = c.div(mu).mulu(uint128(normalizedSharesReserves).pow(a, ONE))) <= MAX, "YieldMath: Rate overflow (za)" ); uint256 ya = fyTokenReserves.pow(a, ONE); require((sum = za + ya) <= MAX, "YieldMath: > fyToken reserves"); } require( (result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves)) <= MAX, "YieldMath: Rounding error" ); fyTokenIn = uint128(result); } }
4,008,187
pragma solidity 0.8.13; import "./PoolToken.sol"; import "./BAllowance.sol"; import "./BInterestRateModel.sol"; import "./BSetter.sol"; import "./BStorage.sol"; import "./interfaces/IBorrowable.sol"; import "./interfaces/ICollateral.sol"; import "./interfaces/IImpermaxCallee.sol"; import "./interfaces/IERC20.sol"; import "./interfaces/IFactory.sol"; import "./interfaces/IBorrowTracker.sol"; import "./libraries/Math.sol"; import "./libraries/Errors.sol"; // TODO: Inherit IBorrowable contract Borrowable is PoolToken, BStorage, BSetter, BInterestRateModel, BAllowance { uint public constant BORROW_FEE = 0; event Borrow(address indexed sender, address indexed borrower, address indexed receiver, uint borrowAmount, uint repayAmount, uint accountBorrowsPrior, uint accountBorrows, uint totalBorrows); event Liquidate(address indexed sender, address indexed borrower, address indexed liquidator, uint seizeTokens, uint repayAmount, uint accountBorrowsPrior, uint accountBorrows, uint totalBorrows); /*** PoolToken ***/ function _update() internal override { super._update(); _calculateBorrowRate(); } function _mintReserves(uint _exchangeRate, uint _totalSupply) internal returns (uint) { uint _exchangeRateLast = exchangeRateLast; if (_exchangeRate > _exchangeRateLast) { uint _exchangeRateNew = _exchangeRate - (((_exchangeRate - _exchangeRateLast) * reserveFactor) / 1e18); uint liquidity = ((_totalSupply * _exchangeRate) / _exchangeRateNew) - _totalSupply; if (liquidity > 0) { address reservesManager = IFactory(factory).reservesManager(); _mint(reservesManager, liquidity); } exchangeRateLast = _exchangeRateNew; return _exchangeRateNew; } else return _exchangeRate; } function exchangeRate() public override accrue returns (uint) { uint _totalSupply = totalSupply; uint _actualBalance = totalBalance + totalBorrows; if (_totalSupply == 0 || _actualBalance == 0) return initialExchangeRate; uint _exchangeRate = (_actualBalance * 1e18) / _totalSupply; return _mintReserves(_exchangeRate, _totalSupply); } // force totalBalance to match real balance function sync() external override nonReentrant update accrue {} /*** Borrowable ***/ // this is the stored borrow balance; the current borrow balance may be slightly higher function borrowBalance(address borrower) public view returns (uint) { BorrowSnapshot memory borrowSnapshot = borrowBalances[borrower]; if (borrowSnapshot.interestIndex == 0) return 0; // not initialized return (uint(borrowSnapshot.principal) * borrowIndex) / borrowSnapshot.interestIndex; } function _trackBorrow(address borrower, uint accountBorrows, uint _borrowIndex) internal { address _borrowTracker = borrowTracker; if (_borrowTracker == address(0)) return; IBorrowTracker(_borrowTracker).trackBorrow(borrower, accountBorrows, _borrowIndex); } function _updateBorrow(address borrower, uint borrowAmount, uint repayAmount) private returns (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) { accountBorrowsPrior = borrowBalance(borrower); if (borrowAmount == repayAmount) return (accountBorrowsPrior, accountBorrowsPrior, totalBorrows); uint112 _borrowIndex = borrowIndex; if (borrowAmount > repayAmount) { BorrowSnapshot storage borrowSnapshot = borrowBalances[borrower]; uint increaseAmount = borrowAmount - repayAmount; accountBorrows = accountBorrowsPrior + increaseAmount; borrowSnapshot.principal = safe112(accountBorrows); borrowSnapshot.interestIndex = _borrowIndex; _totalBorrows = uint(totalBorrows) + increaseAmount; totalBorrows = safe112(_totalBorrows); } else { BorrowSnapshot storage borrowSnapshot = borrowBalances[borrower]; uint decreaseAmount = repayAmount - borrowAmount; accountBorrows = accountBorrowsPrior > decreaseAmount ? accountBorrowsPrior - decreaseAmount : 0; borrowSnapshot.principal = safe112(accountBorrows); if(accountBorrows == 0) { borrowSnapshot.interestIndex = 0; } else { borrowSnapshot.interestIndex = _borrowIndex; } uint actualDecreaseAmount = accountBorrowsPrior - accountBorrows; _totalBorrows = totalBorrows; // gas savings _totalBorrows = _totalBorrows > actualDecreaseAmount ? _totalBorrows - actualDecreaseAmount : 0; totalBorrows = safe112(_totalBorrows); } _trackBorrow(borrower, accountBorrows, _borrowIndex); } // this low-level function should be called from another contract function borrow(address borrower, address receiver, uint borrowAmount, bytes calldata data) external nonReentrant update accrue { uint _totalBalance = totalBalance; _require(borrowAmount <= _totalBalance, Errors.INSUFFICIENT_CASH); _checkBorrowAllowance(borrower, msg.sender, borrowAmount); // optimistically transfer funds if (borrowAmount > 0) _safeTransfer(receiver, borrowAmount); if (data.length > 0) IImpermaxCallee(receiver).impermaxBorrow(msg.sender, borrower, borrowAmount, data); uint balance = IERC20(underlying).balanceOf(address(this)); uint borrowFee = (borrowAmount * BORROW_FEE) / 1e18; uint adjustedBorrowAmount = borrowAmount + borrowFee; uint repayAmount = (balance + borrowAmount) - _totalBalance; (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) = _updateBorrow(borrower, adjustedBorrowAmount, repayAmount); if(adjustedBorrowAmount > repayAmount) _require( ICollateral(collateral).canBorrow(borrower, address(this), accountBorrows), Errors.INSUFFICIENT_LIQUIDITY ); emit Borrow(msg.sender, borrower, receiver, borrowAmount, repayAmount, accountBorrowsPrior, accountBorrows, _totalBorrows); } // this low-level function should be called from another contract function liquidate(address borrower, address liquidator) external nonReentrant update accrue returns (uint seizeTokens) { uint balance = IERC20(underlying).balanceOf(address(this)); uint repayAmount = balance - totalBalance; uint actualRepayAmount = Math.min(borrowBalance(borrower), repayAmount); seizeTokens = ICollateral(collateral).seize(liquidator, borrower, actualRepayAmount); (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) = _updateBorrow(borrower, 0, repayAmount); emit Liquidate(msg.sender, borrower, liquidator, seizeTokens, repayAmount, accountBorrowsPrior, accountBorrows, _totalBorrows); } function trackBorrow(address borrower) external { _trackBorrow(borrower, borrowBalance(borrower), borrowIndex); } modifier accrue() { accrueInterest(); _; } }
this low-level function should be called from another contract optimistically transfer funds
function borrow(address borrower, address receiver, uint borrowAmount, bytes calldata data) external nonReentrant update accrue { uint _totalBalance = totalBalance; _require(borrowAmount <= _totalBalance, Errors.INSUFFICIENT_CASH); _checkBorrowAllowance(borrower, msg.sender, borrowAmount); if (borrowAmount > 0) _safeTransfer(receiver, borrowAmount); if (data.length > 0) IImpermaxCallee(receiver).impermaxBorrow(msg.sender, borrower, borrowAmount, data); uint balance = IERC20(underlying).balanceOf(address(this)); uint borrowFee = (borrowAmount * BORROW_FEE) / 1e18; uint adjustedBorrowAmount = borrowAmount + borrowFee; uint repayAmount = (balance + borrowAmount) - _totalBalance; (uint accountBorrowsPrior, uint accountBorrows, uint _totalBorrows) = _updateBorrow(borrower, adjustedBorrowAmount, repayAmount); if(adjustedBorrowAmount > repayAmount) _require( ICollateral(collateral).canBorrow(borrower, address(this), accountBorrows), Errors.INSUFFICIENT_LIQUIDITY ); emit Borrow(msg.sender, borrower, receiver, borrowAmount, repayAmount, accountBorrowsPrior, accountBorrows, _totalBorrows); }
5,342,670
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/utils/StorageSlot.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "./interfaces/IExternalStorageAccess.sol"; import "hardhat/console.sol"; /// @author Simon Tian /// @title An abstract context base contract abstract contract ContextB is Context { /** * @dev The storage slot of the ExternalStorageAccess contract which defines * the storage for this contract. * This is bytes32(uint256(keccak256('eip1967.proxy.externalStorage')) - 1)) * and is validated in the constructor. */ bytes32 private constant _EXTERNAL_STORAGE_SLOT = 0x5d7876868c9e78cee439e4eef1204b475795cf4ef8060f1ee3848da0b5885cb9; /** * @dev Sets the address of external storage access contract * `externalStorageAccessAddr_` at slot `_EXTERNAL_STORAGE_SLOT`. */ constructor(address externalStorageAccessAddr_) { assert(_EXTERNAL_STORAGE_SLOT == bytes32(uint256(keccak256("eip1967.proxy.externalStorage")) - 1)); StorageSlot.getAddressSlot(_EXTERNAL_STORAGE_SLOT).value = externalStorageAccessAddr_; } /** * @dev Modifier that checks if called by `contractName` */ modifier onlyByContract(string memory contractName) { require(_msgSender() == _getContractAddr(contractName), "Only by contract"); _; } /** * @dev Modifier that checks if called by contracts `contractName1` * and `contractName2`. */ modifier onlyByContracts(string memory contractName1, string memory contractName2) { require( _msgSender() == _getContractAddr(contractName1) || _msgSender() == _getContractAddr(contractName2), "Only by contracts" ); _; } /** * @dev Returns the address of external storage access contract at slot * _EXTERNAL_STORAGE_SLOT. */ function _getExternalStorageAccessAddr() internal view returns (address) { return StorageSlot.getAddressSlot(_EXTERNAL_STORAGE_SLOT).value; } /** * @dev Returns the instantiated interface `IExternalStorageAccess`. */ function _IESA() internal view returns (IExternalStorageAccess) { return IExternalStorageAccess(_getExternalStorageAccessAddr()); } /** * @dev Returns the contract address given contract name `contractName_`. */ function _getContractAddr(string memory contractName_) internal view returns (address) { return _IESA().getContractAddr(contractName_); } }
Returns the address of external storage access contract at slot _EXTERNAL_STORAGE_SLOT./
function _getExternalStorageAccessAddr() internal view returns (address) { return StorageSlot.getAddressSlot(_EXTERNAL_STORAGE_SLOT).value; }
7,311,297
//SPDX-License-Identifier: MIT pragma solidity ^0.8.4; //openzepplin ERC721 NFT functionality import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; // security against transactions for multiple requests import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import "hardhat/console.sol"; contract AvanftMarket is ReentrancyGuard{ using Counters for Counters.Counter; Counters.Counter private _tokenIds; Counters.Counter private _tokensSold; // determine who is the owner of the contract // charge a listing fee address payable owner; // listing price uint256 listingPrice = 0.045 ether; constructor() { //set the owner owner = payable(msg.sender); } struct MarketToken { uint itemId; address nftContract; uint256 tokenId; address payable seller; address payable owner; uint256 price; bool sold; } //tokenId return which marketToken mapping(uint256 => MarketToken) private idToMarketToken; // listen to events from front end applications event MarketTokenMinted( uint indexed itemId, address indexed nftContract, uint256 indexed tokenId, address seller, address owner, uint256 price, bool sold ); // get the listing price function getListingPrice() public view returns (uint256) { return listingPrice; } // two functions to interact with contract // 1. create a market item to put it up for sale // 2. create a market sale fpr buying and selling between parties function makeMarketItem( address nftContract, uint tokenId, uint price ) public payable nonReentrant { // nonReentrant is a modifier to prevent reentry attack require(price >0, 'Price must be atleast one wei'); require(msg.value == listingPrice, 'Price must be equal to listing price'); _tokenIds.increment(); uint itemId = _tokenIds.current(); // putting it up for sale - bool - no owner idToMarketToken[itemId] = MarketToken( itemId, nftContract, tokenId, payable(msg.sender), payable(address(0)), price, false ); // NFT transaction IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); emit MarketTokenMinted( itemId, nftContract, tokenId, msg.sender, address(0), price, false ); } //function to conduct transactions and market sale function createMarketSale( address nftContract, uint itemId) public payable nonReentrant { uint price = idToMarketToken[itemId].price; uint tokenId = idToMarketToken[itemId].tokenId; require(msg.value == price, 'Please submit the asking price in order to contine'); // transfer the amount to seller idToMarketToken[itemId].seller.transfer(msg.value); // transfer the token from contract address to buyer IERC721(nftContract).transferFrom(address(this), msg.sender, tokenId); idToMarketToken[itemId].owner = payable(msg.sender); idToMarketToken[itemId].sold = true; _tokensSold.increment(); payable(owner).transfer(listingPrice); } // function to fetchMarketItmes - minting, buying and selling // return the number of unsold items function fetchMarketTokens() public view returns(MarketToken[] memory) { uint itemCount = _tokenIds.current(); uint unsoldItemCount = _tokenIds.current() - _tokensSold.current(); uint currentIndex = 0; // looping over the number of items created (if number has not been sold pupulte the array) MarketToken[] memory items = new MarketToken[](unsoldItemCount); for(uint i = 0; i < itemCount; i++) { if(idToMarketToken[i+1].owner == address(0)) { uint currentId = i + 1; MarketToken storage currentItem = idToMarketToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // return the NFTs that the user has purchased function fetchMyNFTs() public view returns (MarketToken[] memory) { uint totalItemCount = _tokenIds.current(); // a second counter for each individual user uint itemCount = 0; uint currentIndex = 0; for(uint i = 0; i < totalItemCount; i++) { if(idToMarketToken[i + 1].owner == msg.sender){ itemCount+=1; } } // second loop to loop through the amount you have purchased with itemcount // check to see if the owner address is equal to msg.sender MarketToken[] memory items = new MarketToken[](itemCount); for(uint i = 0; i < totalItemCount; i++) { if(idToMarketToken[i + 1].owner == msg.sender) { uint currentId = idToMarketToken[i + 1].itemId; // current array MarketToken storage currentItem = idToMarketToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } // function for returning an array of minted nfts function fetchItemsCreated() public view returns(MarketToken[] memory) { // instead of .owner it will be the .seller uint totalItemCount = _tokenIds.current(); uint itemCount = 0; uint currentIndex = 0; for(uint i = 0; i < totalItemCount; i++) { if(idToMarketToken[i + 1].seller == msg.sender){ itemCount+=1; } } // second loop to loop through the amount you have purchased with itemcount // check to see if the seller address is equal to msg.sender MarketToken[] memory items = new MarketToken[](itemCount); for(uint i = 0; i < totalItemCount; i++) { if(idToMarketToken[i + 1].seller == msg.sender) { uint currentId = idToMarketToken[i + 1].itemId; // current array MarketToken storage currentItem = idToMarketToken[currentId]; items[currentIndex] = currentItem; currentIndex += 1; } } return items; } }
two functions to interact with contract 1. create a market item to put it up for sale 2. create a market sale fpr buying and selling between parties nonReentrant is a modifier to prevent reentry attack putting it up for sale - bool - no owner NFT transaction
function makeMarketItem( address nftContract, uint tokenId, uint price ) public payable nonReentrant { require(price >0, 'Price must be atleast one wei'); require(msg.value == listingPrice, 'Price must be equal to listing price'); _tokenIds.increment(); uint itemId = _tokenIds.current(); idToMarketToken[itemId] = MarketToken( itemId, nftContract, tokenId, payable(msg.sender), payable(address(0)), price, false ); IERC721(nftContract).transferFrom(msg.sender, address(this), tokenId); emit MarketTokenMinted( itemId, nftContract, tokenId, msg.sender, address(0), price, false ); }
6,400,954
//Address: 0x647f24fc14b75335adf97eb9792ce004471bf35a //Contract name: MitToken //Balance: 0 Ether //Verification Date: 5/24/2018 //Transacion Count: 31 // CODE STARTS HERE pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert_ex(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert_ex(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert_ex(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert_ex(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert_ex(c >= a); 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; } function assert_ex(bool assert_exion) internal pure{ if (!assert_exion) { revert(); } } } contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract ERC20Interface { using SafeMath for uint; uint public _totalSupply; string public name; string public symbol; uint8 public decimals; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed _owner, address indexed _spender, uint _value); function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /** * Set allowed for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { event TokenFallback(address _from, uint _value, bytes _data); /** * @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 _data)public { TokenFallback(_from,_value,_data); } } contract StanderdToken is ERC20Interface, ERC223ReceivingContract, Owned { /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { revert(); } _; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function transferFrom(address _from,address _to, uint _value) public returns (bool) { //require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } } contract PreviligedToken is Owned { using SafeMath for uint; mapping (address => uint) previligedBalances; mapping (address => mapping (address => uint)) previligedallowed; event PreviligedLock(address indexed from, address indexed to, uint value); event PreviligedUnLock(address indexed from, address indexed to, uint value); event Previligedallowed(address indexed _owner, address indexed _spender, uint _value); function previligedBalanceOf(address _owner) public view returns (uint balance) { return previligedBalances[_owner]; } function previligedApprove(address _owner, address _spender, uint _value) onlyOwner public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (previligedallowed[_owner][_spender] != 0)) { revert(); } previligedallowed[_owner][_spender] = _value; Previligedallowed(_owner, _spender, _value); return true; } function getPreviligedallowed(address _owner, address _spender) public view returns (uint remaining) { return previligedallowed[_owner][_spender]; } function previligedAddApproval(address _owner, address _spender, uint _addedValue) onlyOwner public returns (bool) { previligedallowed[_owner][_spender] = previligedallowed[_owner][_spender].add(_addedValue); Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } function previligedSubApproval(address _owner, address _spender, uint _subtractedValue) onlyOwner public returns (bool) { uint oldValue = previligedallowed[_owner][_spender]; if (_subtractedValue > oldValue) { previligedallowed[_owner][_spender] = 0; } else { previligedallowed[_owner][_spender] = oldValue.sub(_subtractedValue); } Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } } contract MitToken is StanderdToken, PreviligedToken { using SafeMath for uint; event Burned(address burner, uint burnedAmount); function MitToken() public { uint initialSupply = 6000000000; decimals = 18; _totalSupply = initialSupply * 10 ** uint(decimals); // Update total supply with the decimal amount balances[msg.sender] = _totalSupply; // Give the creator all initial tokens name = "MitCoin"; // Set the name for display purposes symbol = "MITC"; // Set the symbol for display purposes3 } /** * @dev Function to mint tokens * @notice Create `mintedAmount` tokens and send it to `_target` * @param _target The address that will receive the minted tokens. * @param _mintedAmount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintToken(address _target, uint _mintedAmount) onlyOwner public { balances[_target] = balances[_target].add(_mintedAmount); _totalSupply = _totalSupply.add(_mintedAmount); Transfer(address(0), _target, _mintedAmount); } function burn(uint _amount) onlyOwner public { address burner = msg.sender; balances[burner] = balances[burner].sub(_amount); _totalSupply = _totalSupply.sub(_amount); Burned(burner, _amount); } function previligedLock(address _to, uint _value) onlyOwner public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); //balances[_to] = balances[_to].add(_value); previligedBalances[_to] = previligedBalances[_to].add(_value); PreviligedLock(_from, _to, _value); return true; } function previligedUnLock(address _from, uint _value) public returns (bool) { address to = msg.sender; // we force the address_to to be the the caller require(to != address(0)); require(_value <= previligedBalances[_from]); require(_value <= previligedallowed[_from][msg.sender]); previligedBalances[_from] = previligedBalances[_from].sub(_value); balances[to] = balances[to].add(_value); previligedallowed[_from][msg.sender] = previligedallowed[_from][msg.sender].sub(_value); PreviligedUnLock(_from, to, _value); return true; } }
Set allowed for other address Allows `_spender` to spend no more than `_value` tokens in your behalf _spender The address authorized to spend _value the max amount they can spend/ To change the approve amount you first have to reduce the addresses` allowed to zero by calling `approve(_spender, 0)` if it is not already 0 to mitigate the race condition described here: https:github.com/ethereum/EIPs/issues/20issuecomment-263524729
function approve(address _spender, uint _value) public returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
934,827
pragma solidity >=0.5.0 <0.7.0; /** * @author Ricardo Guilherme Schmidt (Status Research & Development GmbH) * @notice based on https://github.com/ethereum/eth2.0-specs/blob/dev/ssz/merkle-proofs.md#merkle-multiproofs but without generalized indexes */ contract MerkleMultiProof { /** * @notice Calculates a merkle root using multiple leafs at same time * @param leafs out of order sequence of leafs and it's siblings * @param proofs out of order sequence of parent proofs * @param proofFlag flags for using or not proofs while hashing against hashes. * @return merkleRoot of tree */ function calculateMultiMerkleRoot( bytes32[] memory leafs, bytes32[] memory proofs, bool[] memory proofFlag ) public pure returns (bytes32 merkleRoot) { uint256 leafsLen = leafs.length; uint256 totalHashes = proofFlag.length; bytes32[] memory hashes = new bytes32[](totalHashes); uint leafPos = 0; uint hashPos = 0; uint proofPos = 0; for(uint256 i = 0; i < totalHashes; i++){ hashes[i] = hashPair( proofFlag[i] ? (leafPos < leafsLen ? leafs[leafPos++] : hashes[hashPos++]) : proofs[proofPos++], leafPos < leafsLen ? leafs[leafPos++] : hashes[hashPos++] ); } return hashes[totalHashes-1]; } function hashPair(bytes32 a, bytes32 b) private pure returns(bytes32){ return a < b ? hash_node(a, b) : hash_node(b, a); } function hash_node(bytes32 left, bytes32 right) private pure returns (bytes32 hash) { assembly { mstore(0x00, left) mstore(0x20, right) hash := keccak256(0x00, 0x40) } return hash; } /** * @notice Check validity of multimerkle proof * @param root merkle root * @param leafs out of order sequence of leafs and it's siblings * @param proofs out of order sequence of parent proofs * @param proofFlag flags for using or not proofs while hashing against hashes. */ function verifyMultiProof( bytes32 root, bytes32[] memory leafs, bytes32[] memory proofs, bool[] memory proofFlag ) public pure returns (bool) { return calculateMultiMerkleRoot(leafs, proofs, proofFlag) == root; } }
Check validity of multimerkle proof root merkle root leafs out of order sequence of leafs and it's siblings proofs out of order sequence of parent proofs proofFlag flags for using or not proofs while hashing against hashes./
function verifyMultiProof( bytes32 root, bytes32[] memory leafs, bytes32[] memory proofs, bool[] memory proofFlag ) public pure returns (bool) { return calculateMultiMerkleRoot(leafs, proofs, proofFlag) == root; }
12,854,559
./full_match/1/0x2a09bd75fbB293456E33fF180919a704650219b0/sources/browser/chainBridge/SXBridge.sol
(recipient,tokenId,metadata,feeAmount) = abi.decode(asset, (address,uint256, bytes,uint256)) ;
function _decodeAsset(bytes memory asset) internal pure returns( address recipient, uint256 tokenId, bytes memory metadata, uint256 feeAmount) { return abi.decode(asset, (address,uint256, bytes,uint256)); }
16,483,895
./full_match/4/0xb27e7812F0FfBEC13F8F040B367c3438ea2eE38f/sources/contracts/SimpleStorage.sol
if you store object in memory it only be stored during execution. However, if we store it with storgae the data will be stored even after execution
function addPerson (string memory _name, uint256 _favoriteNumber) public{ people.push(People(_favoriteNumber, _name)); nameToFavoriteNumber[_name] = _favoriteNumber; }
709,395
./full_match/42220/0xDD85f95883a8B1836849AC76CBD7F92D1619e4c0/sources/StrategySushiLPV2_flat.sol
Updates router that will be used for swaps. _unirouter new unirouter address./
function setUnirouter(address _unirouter) external onlyOwner { unirouter = _unirouter; }
16,323,571
./full_match/42220/0xDD85f95883a8B1836849AC76CBD7F92D1619e4c0/sources/StrategySushiLPV2_flat.sol
Updates beefy fee recipient. _beefyFeeRecipient new beefy fee recipient address./
function setBeefyFeeRecipient(address _beefyFeeRecipient) external onlyOwner { beefyFeeRecipient = _beefyFeeRecipient; }
16,323,573
./full_match/1/0x6F1bB529BEd91cD7f75b14d68933AeC9d71eb723/sources/contracts/math-utils/common/Uint.sol
does not revert on overflow
function unsafeSub(uint256 x, uint256 y) pure returns (uint256) { unchecked { return x - y; }}
8,295,374
./full_match/1/0xABE46f13C833Ab07bf9e523F485B53c9a633DD60/sources/contracts/IdleCDO.sol
it's REQUIRED to transfer out any incentive tokens accrued before _incentiveTokens array with new incentive tokens
function setIncentiveTokens(address[] memory _incentiveTokens) external { _checkOnlyOwner(); incentiveTokens = _incentiveTokens; }
8,321,930
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../payment/RefundEscrowWithFee.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. */ contract RefundableCrowdsaleWithFee is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund escrow used to hold funds while crowdsale is running RefundEscrow internal escrow; /** * @dev Constructor, creates RefundEscrow. * @param _goal Funding goal */ constructor(uint256 _goal, address _feeWallet, uint8 _feePercent) public { require(_goal > 0, "Goal is zero"); escrow = new RefundEscrowWithFee(wallet, _feeWallet, _feePercent); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized, "Crowdsale is not finalized yet"); require(!goalReached(), "Goal of the crowdsale is reached"); escrow.withdraw(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 escrow finalization task, called when owner calls finalize() */ function finalization() internal { _finilizeEscrow(); super.finalization(); } /** * @dev escrow finalization * Override for other escrow types */ function _finilizeEscrow() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } } /** * @dev Overrides Crowdsale fund forwarding, sending funds to escrow. */ function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } }
Investors can claim refunds here if crowdsale is unsuccessful/
function claimRefund() public { require(isFinalized, "Crowdsale is not finalized yet"); require(!goalReached(), "Goal of the crowdsale is reached"); escrow.withdraw(msg.sender); }
6,356,083
./full_match/51/0x26f0104Fe1d8b10B9876222a39DbddF4b2B7F729/sources/contracts/Whitelist.sol
This function checks if the input address has given role and platform is not in paused state/
function hasAccessRole(bytes32 role, address address_) public view returns (bool) { return hasRole(role, address_); }
13,235,967
//Address: 0xa3e97b1da9c3684324fe38627c40e94555f39b18 //Contract name: Crowdsale //Balance: 0 Ether //Verification Date: 2/18/2018 //Transacion Count: 12 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title ICO CONTRACT * @dev ERC-20 Token Standard Complian */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Crowdsale is Ownable { using SafeMath for uint256; // The token being sold token public token_reward; // start and end timestamps where investments are allowed (both inclusive uint256 public start_time = now; //for testing //uint256 public start_time = 1517846400; //02/05/2018 @ 4:00pm (UTC) or 5 PM (UTC + 1) uint256 public end_Time = 1522454400; // 03/31/2018 @ 12:00am (UTC) uint256 public phase_1_remaining_tokens = 50000000 * (10 ** uint256(8)); uint256 public phase_2_remaining_tokens = 50000000 * (10 ** uint256(8)); uint256 public phase_3_remaining_tokens = 50000000 * (10 ** uint256(8)); uint256 public phase_4_remaining_tokens = 50000000 * (10 ** uint256(8)); uint256 public phase_5_remaining_tokens = 50000000 * (10 ** uint256(8)); uint256 public phase_1_bonus = 40; uint256 public phase_2_bonus = 20; uint256 public phase_3_bonus = 15; uint256 public phase_4_bonus = 10; uint256 public phase_5_bonus = 5; uint256 public token_price = 2;// 2 cents // address where funds are collected address public wallet; // Ether to $ price uint256 public eth_to_usd = 1000; // amount of raised money in wei 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); // rate change event event EthToUsdChanged(address indexed owner, uint256 old_eth_to_usd, uint256 new_eth_to_usd); // constructor function Crowdsale(address tokenContractAddress) public{ wallet = 0x1aC024482b91fa9AaF22450Ff60680BAd60bF8D3;//wallet where ETH will be transferred token_reward = token(tokenContractAddress); } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function getRate() constant public returns (uint256){ return eth_to_usd.mul(100).div(token_price); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= start_time && now <= end_Time; bool allPhaseFinished = phase_5_remaining_tokens > 0; bool nonZeroPurchase = msg.value != 0; bool minPurchase = eth_to_usd*msg.value >= 100; // minimum purchase $100 return withinPeriod && nonZeroPurchase && allPhaseFinished && minPurchase; } // @return true if the admin can send tokens manually function validPurchaseForManual() internal constant returns (bool) { bool withinPeriod = now >= start_time && now <= end_Time; bool allPhaseFinished = phase_5_remaining_tokens > 0; return withinPeriod && allPhaseFinished; } // check token availibility for current phase and max allowed token balance function checkAndUpdateTokenForManual(uint256 _tokens) internal returns (bool){ if(phase_1_remaining_tokens > 0){ if(_tokens > phase_1_remaining_tokens){ uint256 tokens_from_phase_2 = _tokens.sub(phase_1_remaining_tokens); phase_1_remaining_tokens = 0; phase_2_remaining_tokens = phase_2_remaining_tokens.sub(tokens_from_phase_2); }else{ phase_1_remaining_tokens = phase_1_remaining_tokens.sub(_tokens); } return true; }else if(phase_2_remaining_tokens > 0){ if(_tokens > phase_2_remaining_tokens){ uint256 tokens_from_phase_3 = _tokens.sub(phase_2_remaining_tokens); phase_2_remaining_tokens = 0; phase_3_remaining_tokens = phase_3_remaining_tokens.sub(tokens_from_phase_3); }else{ phase_2_remaining_tokens = phase_2_remaining_tokens.sub(_tokens); } return true; }else if(phase_3_remaining_tokens > 0){ if(_tokens > phase_3_remaining_tokens){ uint256 tokens_from_phase_4 = _tokens.sub(phase_3_remaining_tokens); phase_3_remaining_tokens = 0; phase_4_remaining_tokens = phase_4_remaining_tokens.sub(tokens_from_phase_4); }else{ phase_3_remaining_tokens = phase_3_remaining_tokens.sub(_tokens); } return true; }else if(phase_4_remaining_tokens > 0){ if(_tokens > phase_4_remaining_tokens){ uint256 tokens_from_phase_5 = _tokens.sub(phase_4_remaining_tokens); phase_4_remaining_tokens = 0; phase_5_remaining_tokens = phase_5_remaining_tokens.sub(tokens_from_phase_5); }else{ phase_4_remaining_tokens = phase_4_remaining_tokens.sub(_tokens); } return true; }else if(phase_5_remaining_tokens > 0){ if(_tokens > phase_5_remaining_tokens){ return false; }else{ phase_5_remaining_tokens = phase_5_remaining_tokens.sub(_tokens); } }else{ return false; } } // function to transfer token manually function transferManually(uint256 _tokens, address to_address) onlyOwner public returns (bool){ require(to_address != 0x0); require(validPurchaseForManual()); require(checkAndUpdateTokenForManual(_tokens)); token_reward.transfer(to_address, _tokens); return true; } // check token availibility for current phase and max allowed token balance function transferIfTokenAvailable(uint256 _tokens, uint256 _weiAmount, address _beneficiary) internal returns (bool){ uint256 total_token_to_transfer = 0; uint256 bonus = 0; if(phase_1_remaining_tokens > 0){ if(_tokens > phase_1_remaining_tokens){ uint256 tokens_from_phase_2 = _tokens.sub(phase_1_remaining_tokens); bonus = (phase_1_remaining_tokens.mul(phase_1_bonus).div(100)).add(tokens_from_phase_2.mul(phase_2_bonus).div(100)); phase_1_remaining_tokens = 0; phase_2_remaining_tokens = phase_2_remaining_tokens.sub(tokens_from_phase_2); }else{ phase_1_remaining_tokens = phase_1_remaining_tokens.sub(_tokens); bonus = _tokens.mul(phase_1_bonus).div(100); } total_token_to_transfer = _tokens + bonus; }else if(phase_2_remaining_tokens > 0){ if(_tokens > phase_2_remaining_tokens){ uint256 tokens_from_phase_3 = _tokens.sub(phase_2_remaining_tokens); bonus = (phase_2_remaining_tokens.mul(phase_2_bonus).div(100)).add(tokens_from_phase_3.mul(phase_3_bonus).div(100)); phase_2_remaining_tokens = 0; phase_3_remaining_tokens = phase_3_remaining_tokens.sub(tokens_from_phase_3); }else{ phase_2_remaining_tokens = phase_2_remaining_tokens.sub(_tokens); bonus = _tokens.mul(phase_2_bonus).div(100); } total_token_to_transfer = _tokens + bonus; }else if(phase_3_remaining_tokens > 0){ if(_tokens > phase_3_remaining_tokens){ uint256 tokens_from_phase_4 = _tokens.sub(phase_3_remaining_tokens); bonus = (phase_3_remaining_tokens.mul(phase_3_bonus).div(100)).add(tokens_from_phase_4.mul(phase_4_bonus).div(100)); phase_3_remaining_tokens = 0; phase_4_remaining_tokens = phase_4_remaining_tokens.sub(tokens_from_phase_4); }else{ phase_3_remaining_tokens = phase_3_remaining_tokens.sub(_tokens); bonus = _tokens.mul(phase_3_bonus).div(100); } total_token_to_transfer = _tokens + bonus; }else if(phase_4_remaining_tokens > 0){ if(_tokens > phase_4_remaining_tokens){ uint256 tokens_from_phase_5 = _tokens.sub(phase_4_remaining_tokens); bonus = (phase_4_remaining_tokens.mul(phase_4_bonus).div(100)).add(tokens_from_phase_5.mul(phase_5_bonus).div(100)); phase_4_remaining_tokens = 0; phase_5_remaining_tokens = phase_5_remaining_tokens.sub(tokens_from_phase_5); }else{ phase_4_remaining_tokens = phase_4_remaining_tokens.sub(_tokens); bonus = _tokens.mul(phase_4_bonus).div(100); } total_token_to_transfer = _tokens + bonus; }else if(phase_5_remaining_tokens > 0){ if(_tokens > phase_5_remaining_tokens){ total_token_to_transfer = 0; }else{ phase_5_remaining_tokens = phase_5_remaining_tokens.sub(_tokens); bonus = _tokens.mul(phase_5_bonus).div(100); total_token_to_transfer = _tokens + bonus; } }else{ total_token_to_transfer = 0; } if(total_token_to_transfer > 0){ token_reward.transfer(_beneficiary, total_token_to_transfer); TokenPurchase(msg.sender, _beneficiary, _weiAmount, total_token_to_transfer); return true; }else{ return false; } } // fallback function can be used to buy tokens function () payable public{ buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = (weiAmount.mul(getRate())).div(10 ** uint256(10)); // Check is there are enough token available for current phase and per person require(transferIfTokenAvailable(tokens, weiAmount, beneficiary)); // update state weiRaised = weiRaised.add(weiAmount); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > end_Time; } // function to transfer token back to owner function transferBack(uint256 tokens, address to_address) onlyOwner public returns (bool){ token_reward.transfer(to_address, tokens); return true; } // function to change rate function changeEth_to_usd(uint256 _eth_to_usd) onlyOwner public returns (bool){ EthToUsdChanged(msg.sender, eth_to_usd, _eth_to_usd); eth_to_usd = _eth_to_usd; return true; } }
return true if crowdsale event has ended
function hasEnded() public constant returns (bool) { return now > end_Time; }
2,501,695
/** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; pragma experimental ABIEncoderV2; import "State.sol"; import "LoanMaintenanceEvents.sol"; import "PausableGuardian.sol"; import "InterestHandler.sol"; import "InterestOracle.sol"; import "TickMathV1.sol"; contract LoanMaintenance_2 is State, LoanMaintenanceEvents, PausableGuardian, InterestHandler { function initialize( address target) external onlyOwner { _setTarget(this.transferLoan.selector, target); _setTarget(this.settleInterest.selector, target); _setTarget(this.getInterestModelValues.selector, target); _setTarget(this.getTWAI.selector, target); } function getInterestModelValues( address pool, bytes32 loanId) external view returns ( uint256 _poolLastUpdateTime, uint256 _poolPrincipalTotal, uint256 _poolInterestTotal, uint256 _poolRatePerTokenStored, uint256 _poolLastInterestRate, uint256 _loanPrincipalTotal, uint256 _loanInterestTotal, uint256 _loanRatePerTokenPaid) { _poolLastUpdateTime = poolLastUpdateTime[pool]; _poolPrincipalTotal = poolPrincipalTotal[pool]; _poolInterestTotal = poolInterestTotal[pool]; _poolRatePerTokenStored = poolRatePerTokenStored[pool]; _poolLastInterestRate = poolLastInterestRate[pool]; _loanPrincipalTotal = loans[loanId].principal; _loanInterestTotal = loanInterestTotal[loanId]; _loanRatePerTokenPaid = loanRatePerTokenPaid[loanId]; } function transferLoan( bytes32 loanId, address newOwner) external nonReentrant pausable { Loan storage loanLocal = loans[loanId]; address currentOwner = loanLocal.borrower; require(loanLocal.active, "loan is closed"); require(currentOwner != newOwner, "no owner change"); require( msg.sender == currentOwner || delegatedManagers[loanId][msg.sender], "unauthorized" ); require(borrowerLoanSets[currentOwner].removeBytes32(loanId), "error in transfer"); borrowerLoanSets[newOwner].addBytes32(loanId); loanLocal.borrower = newOwner; emit TransferLoan( currentOwner, newOwner, loanId ); } function settleInterest( bytes32 loanId) external pausable { // only callable by loan pools require(loanPoolToUnderlying[msg.sender] != address(0), "not authorized"); _settleInterest( msg.sender, // loan pool loanId ); } function getTWAI( address pool) external view returns (uint256) { uint32 timeSinceUpdate = uint32(block.timestamp.sub(poolLastUpdateTime[pool])); return TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean( uint32(block.timestamp), [timeSinceUpdate+twaiLength, timeSinceUpdate], timeSinceUpdate >= 60 ? TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])) : poolInterestRateObservations[pool][poolLastIdx[pool]].tick, poolLastIdx[pool], uint8(-1) )); } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Constants.sol"; import "Objects.sol"; import "EnumerableBytes32Set.sol"; import "ReentrancyGuard.sol"; import "InterestOracle.sol"; import "Ownable.sol"; import "SafeMath.sol"; contract State is Constants, Objects, ReentrancyGuard, Ownable { using SafeMath for uint256; using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set; address public priceFeeds; // handles asset reference price lookups address public swapsImpl; // handles asset swaps using dex liquidity mapping (bytes4 => address) public logicTargets; // implementations of protocol functions mapping (bytes32 => Loan) public loans; // loanId => Loan mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved // Interest mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object (depreciated) mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object (depreciated) // Internals EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set address public feesController; // address controlling fee withdrawals uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid) uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid) uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid) uint256 public protocolTokenHeld; // current protocol token deposit balance uint256 public protocolTokenPaid; // lifetime total payout of protocol token uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying mapping (address => address) public underlyingToLoanPool; // underlying => loanPool EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set mapping (address => bool) public supportedTokens; // supported tokens for swaps uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH /**** new interest model start */ mapping(address => uint256) public poolLastUpdateTime; // per itoken mapping(address => uint256) public poolPrincipalTotal; // per itoken mapping(address => uint256) public poolInterestTotal; // per itoken mapping(address => uint256) public poolRatePerTokenStored; // per itoken mapping(bytes32 => uint256) public loanInterestTotal; // per loan mapping(bytes32 => uint256) public loanRatePerTokenPaid; // per loan mapping(address => uint256) internal poolLastInterestRate; // per itoken mapping(address => InterestOracle.Observation[256]) internal poolInterestRateObservations; // per itoken mapping(address => uint8) internal poolLastIdx; // per itoken uint32 public timeDelta; uint32 public twaiLength; /**** new interest model end */ function _setTarget( bytes4 sig, address target) internal { logicTargets[sig] = target; if (target != address(0)) { logicTargetsSet.addBytes32(bytes32(sig)); } else { logicTargetsSet.removeBytes32(bytes32(sig)); } } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "IWethERC20.sol"; contract Constants { uint256 internal constant WEI_PRECISION = 10**18; uint256 internal constant WEI_PERCENT_PRECISION = 10**20; uint256 internal constant DAYS_IN_A_YEAR = 365; uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month // string internal constant UserRewardsID = "UserRewards"; // decommissioned string internal constant LoanDepositValueID = "LoanDepositValue"; IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // mainnet address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; // mainnet address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; // mainnet address public constant OOKI = address(0x0De05F6447ab4D22c8827449EE4bA2D5C288379B); // mainnet //IWethERC20 public constant wethToken = IWethERC20(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // kovan //address public constant bzrxTokenAddress = 0xB54Fc2F2ea17d798Ad5C7Aba2491055BCeb7C6b2; // kovan //address public constant vbzrxTokenAddress = 0x6F8304039f34fd6A6acDd511988DCf5f62128a32; // kovan //IWethERC20 public constant wethToken = IWethERC20(0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6); // local testnet only //address public constant bzrxTokenAddress = 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87; // local testnet only //address public constant vbzrxTokenAddress = 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472; // local testnet only //IWethERC20 public constant wethToken = IWethERC20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); // bsc (Wrapped BNB) //address public constant bzrxTokenAddress = address(0); // bsc //address public constant vbzrxTokenAddress = address(0); // bsc //address public constant OOKI = address(0); // bsc // IWethERC20 public constant wethToken = IWethERC20(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); // polygon (Wrapped MATIC) // address public constant bzrxTokenAddress = address(0); // polygon // address public constant vbzrxTokenAddress = address(0); // polygon // address public constant OOKI = 0xCd150B1F528F326f5194c012f32Eb30135C7C2c9; // polygon //IWethERC20 public constant wethToken = IWethERC20(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); // avax (Wrapped AVAX) //address public constant bzrxTokenAddress = address(0); // avax //address public constant vbzrxTokenAddress = address(0); // avax // IWethERC20 public constant wethToken = IWethERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); // arbitrum // address public constant bzrxTokenAddress = address(0); // arbitrum // address public constant vbzrxTokenAddress = address(0); // arbitrum // address public constant OOKI = address(0x400F3ff129Bc9C9d239a567EaF5158f1850c65a4); // arbitrum } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; import "IWeth.sol"; import "IERC20.sol"; contract IWethERC20 is IWeth, IERC20 {} /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; interface IWeth { function deposit() external payable; function withdraw(uint256 wad) external; } 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); } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "LoanStruct.sol"; import "LoanParamsStruct.sol"; import "OrderStruct.sol"; import "LenderInterestStruct.sol"; import "LoanInterestStruct.sol"; contract Objects is LoanStruct, LoanParamsStruct, OrderStruct, LenderInterestStruct, LoanInterestStruct {} /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanStruct { struct Loan { bytes32 id; // id of the loan bytes32 loanParamsId; // the linked loan params id bytes32 pendingTradesId; // the linked pending trades id uint256 principal; // total borrowed amount outstanding uint256 collateral; // total collateral escrowed for the loan uint256 startTimestamp; // loan start time uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time uint256 startMargin; // initial margin when the loan opened uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken address borrower; // borrower of this loan address lender; // lender of this loan bool active; // if false, the loan has been fully closed } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanParamsStruct { struct LoanParams { bytes32 id; // id of loan params object bool active; // if false, this object has been disabled by the owner and can't be used for future loans address owner; // owner of this object address loanToken; // the token being loaned address collateralToken; // the required collateral token uint256 minInitialMargin; // the minimum allowed initial margin uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract OrderStruct { struct Order { uint256 lockedAmount; // escrowed amount waiting for a counterparty uint256 interestRate; // interest rate defined by the creator of this order uint256 minLoanTerm; // minimum loan term allowed uint256 maxLoanTerm; // maximum loan term allowed uint256 createdTimestamp; // timestamp when this order was created uint256 expirationTimestamp; // timestamp when this order expires } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LenderInterestStruct { struct LenderInterest { uint256 principalTotal; // total borrowed amount outstanding of asset (DEPRECIATED) uint256 owedPerDay; // interest owed per day for all loans of asset (DEPRECIATED) uint256 owedTotal; // total interest owed for all loans of asset (DEPRECIATED) uint256 paidTotal; // total interest paid so far for asset (DEPRECIATED) uint256 updatedTimestamp; // last update (DEPRECIATED) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanInterestStruct { struct LoanInterest { uint256 owedPerDay; // interest owed per day for loan (DEPRECIATED) uint256 depositTotal; // total escrowed interest for loan (DEPRECIATED) uint256 updatedTimestamp; // last update (DEPRECIATED) } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; /** * @dev Library for managing loan sets * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`. * */ library EnumerableBytes32Set { struct Bytes32Set { // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) index; bytes32[] values; } /** * @dev Add an address value to a set. O(1). * Returns false if the value was already in the set. */ function addAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return addBytes32(set, value); } /** * @dev Add a value to a set. O(1). * Returns false if the value was already in the set. */ function addBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (!contains(set, value)){ set.index[value] = set.values.push(value); return true; } else { return false; } } /** * @dev Removes an address value from a set. O(1). * Returns false if the value was not present in the set. */ function removeAddress(Bytes32Set storage set, address addrvalue) internal returns (bool) { bytes32 value; assembly { value := addrvalue } return removeBytes32(set, value); } /** * @dev Removes a value from a set. O(1). * Returns false if the value was not present in the set. */ function removeBytes32(Bytes32Set storage set, bytes32 value) internal returns (bool) { if (contains(set, value)){ uint256 toDeleteIndex = set.index[value] - 1; uint256 lastIndex = set.values.length - 1; // If the element we're deleting is the last one, we can just remove it without doing a swap if (lastIndex != toDeleteIndex) { bytes32 lastValue = set.values[lastIndex]; // Move the last value to the index where the deleted value is set.values[toDeleteIndex] = lastValue; // Update the index for the moved value set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based } // Delete the index entry for the deleted value delete set.index[value]; // Delete the old entry for the moved value set.values.pop(); return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return set.index[value] != 0; } /** * @dev Returns true if the value is in the set. O(1). */ function containsAddress(Bytes32Set storage set, address addrvalue) internal view returns (bool) { bytes32 value; assembly { value := addrvalue } return set.index[value] != 0; } /** * @dev Returns an array with all values in the set. O(N). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * WARNING: This function may run out of gas on large sets: use {length} and * {get} instead in these cases. */ function enumerate(Bytes32Set storage set, uint256 start, uint256 count) internal view returns (bytes32[] memory output) { uint256 end = start + count; require(end >= start, "addition overflow"); end = set.values.length < end ? set.values.length : end; if (end == 0 || start >= end) { return output; } output = new bytes32[](end-start); for (uint256 i = start; i < end; i++) { output[i-start] = set.values[i]; } return output; } /** * @dev Returns the number of elements on the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return set.values.length; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function get(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return set.values[index]; } /** @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function getAddress(Bytes32Set storage set, uint256 index) internal view returns (address) { bytes32 value = set.values[index]; address addrvalue; assembly { addrvalue := value } return addrvalue; } } pragma solidity >=0.5.0 <0.6.0; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <[email protected]π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs. /// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056 uint256 internal constant REENTRANCY_GUARD_FREE = 1; /// @dev Constant for locked guard state uint256 internal constant REENTRANCY_GUARD_LOCKED = 2; /** * @dev We use a single lock for the whole contract. */ uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE; /** * @dev Prevents a contract from calling itself, directly or indirectly. * 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 an `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant"); reentrancyLock = REENTRANCY_GUARD_LOCKED; _; reentrancyLock = REENTRANCY_GUARD_FREE; } } pragma solidity ^0.5.0; library InterestOracle { struct Observation { uint32 blockTimestamp; int56 irCumulative; int24 tick; } /// @param last The specified observation /// @param blockTimestamp The new timestamp /// @param tick The active tick /// @return Observation The newly populated observation function convert( Observation memory last, uint32 blockTimestamp, int24 tick ) private pure returns (Observation memory) { return Observation({ blockTimestamp: blockTimestamp, irCumulative: last.irCumulative + int56(tick) * (blockTimestamp - last.blockTimestamp), tick: tick }); } /// @param self oracle array /// @param index most recent observation index /// @param blockTimestamp timestamp of observation /// @param tick active tick /// @param cardinality populated elements /// @param minDelta minimum time delta between observations /// @return indexUpdated The new index function write( Observation[256] storage self, uint8 index, uint32 blockTimestamp, int24 tick, uint8 cardinality, uint32 minDelta ) internal returns (uint8 indexUpdated) { Observation memory last = self[index]; // early return if we've already written an observation in last minDelta seconds if (last.blockTimestamp + minDelta >= blockTimestamp) return index; indexUpdated = (index + 1) % cardinality; self[indexUpdated] = convert(last, blockTimestamp, tick); } /// @param self oracle array /// @param target targeted timestamp to retrieve value /// @param index latest index /// @param cardinality populated elements function binarySearch( Observation[256] storage self, uint32 target, uint8 index, uint8 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 l = (index + 1) % cardinality; // oldest observation uint256 r = l + cardinality - 1; // newest observation uint256 i; while (true) { i = (l + r) / 2; beforeOrAt = self[i % cardinality]; if (beforeOrAt.blockTimestamp == 0) { l = 0; r = index; continue; } atOrAfter = self[(i + 1) % cardinality]; bool targetAtOrAfter = beforeOrAt.blockTimestamp <= target; bool targetBeforeOrAt = atOrAfter.blockTimestamp >= target; if (!targetAtOrAfter) { r = i - 1; continue; } else if (!targetBeforeOrAt) { l = i + 1; continue; } break; } } /// @param self oracle array /// @param target targeted timestamp to retrieve value /// @param tick current tick /// @param index latest index /// @param cardinality populated elements function getSurroundingObservations( Observation[256] storage self, uint32 target, int24 tick, uint8 index, uint8 cardinality ) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { beforeOrAt = self[index]; if (beforeOrAt.blockTimestamp <= target) { if (beforeOrAt.blockTimestamp == target) { return (beforeOrAt, atOrAfter); } else { return (beforeOrAt, convert(beforeOrAt, target, tick)); } } beforeOrAt = self[(index + 1) % cardinality]; if (beforeOrAt.blockTimestamp == 0) beforeOrAt = self[0]; require(beforeOrAt.blockTimestamp <= target && beforeOrAt.blockTimestamp != 0, "OLD"); return binarySearch(self, target, index, cardinality); } /// @param self oracle array /// @param time current timestamp /// @param secondsAgo lookback time /// @param index latest index /// @param cardinality populated elements /// @return irCumulative cumulative interest rate, calculated with rate * time function observeSingle( Observation[256] storage self, uint32 time, uint32 secondsAgo, int24 tick, uint8 index, uint8 cardinality ) internal view returns (int56 irCumulative) { if (secondsAgo == 0) { Observation memory last = self[index]; if (last.blockTimestamp != time) { last = convert(last, time, tick); } return last.irCumulative; } uint32 target = time - secondsAgo; (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations(self, target, tick, index, cardinality); if (target == beforeOrAt.blockTimestamp) { // left boundary return beforeOrAt.irCumulative; } else if (target == atOrAfter.blockTimestamp) { // right boundary return atOrAfter.irCumulative; } else { // middle return beforeOrAt.irCumulative + ((atOrAfter.irCumulative - beforeOrAt.irCumulative) / (atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp)) * (target - beforeOrAt.blockTimestamp); } } /// @param self oracle array /// @param time current timestamp /// @param secondsAgos lookback time /// @param index latest index /// @param cardinality populated elements /// @return irCumulative cumulative interest rate, calculated with rate * time function arithmeticMean( Observation[256] storage self, uint32 time, uint32[2] memory secondsAgos, int24 tick, uint8 index, uint8 cardinality ) internal view returns (int24) { int56 firstPoint = observeSingle(self, time, secondsAgos[1], tick, index, cardinality); int56 secondPoint = observeSingle(self, time, secondsAgos[0], tick, index, cardinality); return int24((firstPoint-secondPoint) / (secondsAgos[0]-secondsAgos[1])); } } 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 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract LoanMaintenanceEvents { event DepositCollateral( address indexed user, address indexed depositToken, bytes32 indexed loanId, uint256 depositAmount ); event WithdrawCollateral( address indexed user, address indexed withdrawToken, bytes32 indexed loanId, uint256 withdrawAmount ); // DEPRECATED event ExtendLoanDuration( address indexed user, address indexed depositToken, bytes32 indexed loanId, uint256 depositAmount, uint256 collateralUsedAmount, uint256 newEndTimestamp ); // DEPRECATED event ReduceLoanDuration( address indexed user, address indexed withdrawToken, bytes32 indexed loanId, uint256 withdrawAmount, uint256 newEndTimestamp ); event LoanDeposit( bytes32 indexed loanId, uint256 depositValueAsLoanToken, uint256 depositValueAsCollateralToken ); // DEPRECATED event ClaimReward( address indexed user, address indexed receiver, address indexed token, uint256 amount ); event TransferLoan( address indexed currentOwner, address indexed newOwner, bytes32 indexed loanId ); enum LoanType { All, Margin, NonMargin } struct LoanReturnData { bytes32 loanId; // id of the loan uint96 endTimestamp; // loan end timestamp address loanToken; // loan token address address collateralToken; // collateral token address uint256 principal; // principal amount of the loan uint256 collateral; // collateral amount of the loan uint256 interestOwedPerDay; // interest owned per day uint256 interestDepositRemaining; // remaining unspent interest uint256 startRate; // collateralToLoanRate uint256 startMargin; // margin with which loan was open uint256 maintenanceMargin; // maintenance margin uint256 currentMargin; /// current margin uint256 maxLoanTerm; // maximum term of the loan uint256 maxLiquidatable; // current max liquidatable uint256 maxSeizable; // current max seizable uint256 depositValueAsLoanToken; // net value of deposit denominated as loanToken uint256 depositValueAsCollateralToken; // net value of deposit denominated as collateralToken } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "Ownable.sol"; contract PausableGuardian is Ownable { // keccak256("Pausable_FunctionPause") bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047; // keccak256("Pausable_GuardianAddress") bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf; modifier pausable { require(!_isPaused(msg.sig), "paused"); _; } modifier onlyGuardian { require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized"); _; } function _isPaused(bytes4 sig) public view returns (bool isPaused) { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { isPaused := sload(slot) } } function toggleFunctionPause(bytes4 sig) public onlyGuardian { bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 1) } } function toggleFunctionUnPause(bytes4 sig) public onlyGuardian { // only DAO can unpause, and adding guardian temporarily bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause)); assembly { sstore(slot, 0) } } function changeGuardian(address newGuardian) public onlyGuardian { assembly { sstore(Pausable_GuardianAddress, newGuardian) } } function getGuardian() public view returns (address guardian) { assembly { guardian := sload(Pausable_GuardianAddress) } } function pause(bytes4 [] calldata sig) external onlyGuardian { for(uint256 i = 0; i < sig.length; ++i){ toggleFunctionPause(sig[i]); } } function unpause(bytes4 [] calldata sig) external onlyGuardian { for(uint256 i = 0; i < sig.length; ++i){ toggleFunctionUnPause(sig[i]); } } } /** * Copyright 2017-2021, bZxDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; import "State.sol"; import "ILoanPool.sol"; import "MathUtil.sol"; import "InterestRateEvents.sol"; import "InterestOracle.sol"; import "TickMathV1.sol"; contract InterestHandler is State, InterestRateEvents { using MathUtil for uint256; using InterestOracle for InterestOracle.Observation[256]; // returns up to date loan interest or 0 if not applicable function _settleInterest( address pool, bytes32 loanId) internal returns (uint256 _loanInterestTotal) { poolLastIdx[pool] = poolInterestRateObservations[pool].write( poolLastIdx[pool], uint32(block.timestamp), TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])), uint8(-1), timeDelta ); uint256[7] memory interestVals = _settleInterest2( pool, loanId, false ); poolInterestTotal[pool] = interestVals[1]; poolRatePerTokenStored[pool] = interestVals[2]; if (interestVals[3] != 0) { poolLastInterestRate[pool] = interestVals[3]; emit PoolInterestRateVals( pool, interestVals[0], interestVals[1], interestVals[2], interestVals[3] ); } if (loanId != 0) { _loanInterestTotal = interestVals[5]; loanInterestTotal[loanId] = _loanInterestTotal; loanRatePerTokenPaid[loanId] = interestVals[6]; emit LoanInterestRateVals( loanId, interestVals[4], interestVals[5], interestVals[6] ); } poolLastUpdateTime[pool] = block.timestamp; } function _getPoolPrincipal( address pool) internal view returns (uint256) { uint256[7] memory interestVals = _settleInterest2( pool, 0, true ); return interestVals[0] // _poolPrincipalTotal .add(interestVals[1]); // _poolInterestTotal } function _getLoanPrincipal( address pool, bytes32 loanId) internal view returns (uint256) { uint256[7] memory interestVals = _settleInterest2( pool, loanId, false ); return interestVals[4] // _loanPrincipalTotal .add(interestVals[5]); // _loanInterestTotal } function _settleInterest2( address pool, bytes32 loanId, bool includeLendingFee) internal view returns (uint256[7] memory interestVals) { /* uint256[7] -> 0: _poolPrincipalTotal, 1: _poolInterestTotal, 2: _poolRatePerTokenStored, 3: _poolNextInterestRate, 4: _loanPrincipalTotal, 5: _loanInterestTotal, 6: _loanRatePerTokenPaid */ interestVals[0] = poolPrincipalTotal[pool] .add(lenderInterest[pool][loanPoolToUnderlying[pool]].principalTotal); // backwards compatibility interestVals[1] = poolInterestTotal[pool]; uint256 lendingFee = interestVals[1] .mul(lendingFeePercent) .divCeil(WEI_PERCENT_PRECISION); uint256 _poolVariableRatePerTokenNewAmount; (_poolVariableRatePerTokenNewAmount, interestVals[3]) = _getRatePerTokenNewAmount(pool, interestVals[0].add(interestVals[1] - lendingFee)); interestVals[1] = interestVals[0] .mul(_poolVariableRatePerTokenNewAmount) .div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .add(interestVals[1]); if (includeLendingFee) { interestVals[1] -= lendingFee; } interestVals[2] = poolRatePerTokenStored[pool] .add(_poolVariableRatePerTokenNewAmount); if (loanId != 0 && (interestVals[4] = loans[loanId].principal) != 0) { interestVals[5] = interestVals[4] .mul(interestVals[2].sub(loanRatePerTokenPaid[loanId])) // _loanRatePerTokenUnpaid .div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION) .add(loanInterestTotal[loanId]); interestVals[6] = interestVals[2]; } } function _getRatePerTokenNewAmount( address pool, uint256 poolTotal) internal view returns (uint256 ratePerTokenNewAmount, uint256 nextInterestRate) { uint256 timeSinceUpdate = block.timestamp.sub(poolLastUpdateTime[pool]); uint256 benchmarkRate = TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean( uint32(block.timestamp), [uint32(timeSinceUpdate+twaiLength), uint32(timeSinceUpdate)], poolInterestRateObservations[pool][poolLastIdx[pool]].tick, poolLastIdx[pool], uint8(-1) )); if (timeSinceUpdate != 0 && (nextInterestRate = ILoanPool(pool)._nextBorrowInterestRate(poolTotal, 0, benchmarkRate)) != 0) { ratePerTokenNewAmount = timeSinceUpdate .mul(nextInterestRate) // rate per year .mul(WEI_PERCENT_PRECISION) .div(31536000); // seconds in a year } } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.6.0; interface ILoanPool { function tokenPrice() external view returns (uint256 price); function borrowInterestRate() external view returns (uint256); function _nextBorrowInterestRate( uint256 totalBorrow, uint256 newBorrow, uint256 lastInterestRate) external view returns (uint256 nextRate); function totalAssetSupply() external view returns (uint256); function assetBalanceOf( address _owner) external view returns (uint256); } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity >=0.5.0 <0.8.0; library MathUtil { /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return divCeil(a, b, "SafeMath: division by zero"); } /** * @dev Integer division of two numbers, rounding up and truncating the quotient */ function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b != 0, errorMessage); if (a == 0) { return 0; } uint256 c = ((a - 1) / b) + 1; return c; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } /** * Copyright 2017-2022, OokiDao. All Rights Reserved. * Licensed under the Apache License, Version 2.0. */ pragma solidity 0.5.17; contract InterestRateEvents { event PoolInterestRateVals( address indexed pool, uint256 poolPrincipalTotal, uint256 poolInterestTotal, uint256 poolRatePerTokenStored, uint256 poolNextInterestRate ); event LoanInterestRateVals( bytes32 indexed loanId, uint256 loanPrincipalTotal, uint256 loanInterestTotal, uint256 loanRatePerTokenPaid ); } // 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 TickMathV1 { /// @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) public 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 = uint256(-1) / 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) public 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; } }
last The specified observation blockTimestamp The new timestamp tick The active tick return Observation The newly populated observation
function convert( Observation memory last, uint32 blockTimestamp, int24 tick ) private pure returns (Observation memory) { return Observation({ blockTimestamp: blockTimestamp, irCumulative: last.irCumulative + int56(tick) * (blockTimestamp - last.blockTimestamp), tick: tick }); }
213,897
./full_match/1/0x1A6a41b7adaE4dDb59A50c0cef0B0B62080Ac5F8/sources/NFT-Cashier/Cashier.sol
update the pause purchase status/
function updatePausePurchase(bool status) public onlyOwner { paused_purchase = status; emit UpdatePausePurchase(paused_purchase); }
16,494,656
pragma solidity ^0.5.0; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/IFantomDeFiTokenRegistry.sol"; import "../interfaces/IERC20Detailed.sol"; /** * This utility contract implements an update aware list of * DeFi tokens used across Fantom DeFi protocols. * * version 0.1.0 * license MIT * author Fantom Foundation, Jiri Malek */ contract FantomDeFiTokenRegistry is Ownable, IFantomDeFiTokenRegistry { // TokenInformation represents a single token handled by the registry. // The DeFi API uses this reference to do on-chain tokens tracking. struct TokenInformation { uint256 id; // Internal id of the token (index starting from 1) string name; // Name of the token string symbol; // symbol of the token uint8 decimals; // number of decimals of the token string logo; // URL address of the token logo address oracle; // address of the token price oracle uint8 priceDecimals; // number of decimals the token's price oracle uses bool isActive; // is this token active in DeFi? bool canDeposit; // is this token available for deposit? bool canMint; // is this token available for minting? bool canBorrow; // is this token available for fLend? bool canTrade; // is this token available for direct fTrade? } // tokens is the mapping between the token address and it's detailed information. mapping(address => TokenInformation) public tokens; // tokensList is the list of tokens handled by the registry. address[] public tokensList; // TokenAdded event is emitted when a new token information is added to the contract. event TokenAdded(address indexed token, string name, uint256 index); // TokenUpdated event is emitted when an existing token information is updated. event TokenUpdated(address indexed token, string name); // --------------------------------- // tokens registry view functions // --------------------------------- // tokensCount returns the total number of tokens in the registry. function tokensCount() public view returns (uint256) { return tokensList.length; } // tokenPriceDecimals returns the number of decimal places a price // returned for the given token will be encoded to. function tokenPriceDecimals(address _token) public view returns (uint8) { return tokens[_token].priceDecimals; } // isActive informs if the specified token is active and can be used in DeFi protocols. function isActive(address _token) external view returns (bool) { return tokens[_token].isActive; } // canDeposit informs if the specified token can be deposited to collateral pool. function canDeposit(address _token) external view returns (bool) { return tokens[_token].canDeposit; } // canMint informs if the specified token can be minted in Fantom DeFi. function canMint(address _token) external view returns (bool) { return tokens[_token].canMint; } // canBorrow informs if the specified token can be borrowed in Fantom DeFi. function canBorrow(address _token) external view returns (bool) { return tokens[_token].canBorrow; } // canTrade informs if the specified token can be traded directly in Fantom DeFi. function canTrade(address _token) external view returns (bool) { return tokens[_token].canTrade; } // --------------------------------- // tokens management // --------------------------------- // addToken adds new token into the reference contract. function addToken( address _token, string calldata _logo, address _oracle, uint8 _priceDecimals, bool _isActive, bool _canDeposit, bool _canMint, bool _canBorrow, bool _canTrade ) external onlyOwner { // make sure the token does not exist yet require(0 == tokens[_token].id, "token already known"); // pull decimals from the ERC20 token uint8 _decimals = IERC20Detailed(_token).decimals(); require(_decimals > 0, "token decimals invalid"); // add the token address to the list tokensList.push(_token); // get the token name string memory _name = IERC20Detailed(_token).name(); // create and store the token information tokens[_token] = TokenInformation({ id : tokensList.length, name : _name, symbol : IERC20Detailed(_token).symbol(), decimals : _decimals, logo: _logo, oracle : _oracle, priceDecimals : _priceDecimals, isActive : _isActive, canDeposit : _canDeposit, canMint : _canMint, canBorrow : _canBorrow, canTrade : _canTrade }); // inform emit TokenAdded(_token, _name, tokensList.length - 1); } // updateToken modifies existing token in the reference contract. function updateToken( address _token, string calldata _logo, address _oracle, uint8 _priceDecimals, bool _isActive, bool _canDeposit, bool _canMint, bool _canBorrow, bool _canTrade ) external onlyOwner { // make sure the token exists require(0 != tokens[_token].id, "token unknown"); // update token details in the contract tokens[_token].logo = _logo; tokens[_token].oracle = _oracle; tokens[_token].priceDecimals = _priceDecimals; tokens[_token].isActive = _isActive; tokens[_token].canDeposit = _canDeposit; tokens[_token].canDeposit = _canMint; tokens[_token].canBorrow = _canBorrow; tokens[_token].canTrade = _canTrade; // inform emit TokenUpdated(_token, tokens[_token].name); } }
canDeposit informs if the specified token can be deposited to collateral pool.
function canDeposit(address _token) external view returns (bool) { return tokens[_token].canDeposit; }
6,404,554
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.9; import { IJustCausePool, IJCDepositorERC721, IERC20, IPool, IPoolAddressesProvider, IWETHGateway } from './Interfaces.sol'; import { JCDepositorERC721 } from './JCDepositorERC721.sol'; import { JustCausePoolAaveV3 } from './JustCausePoolAaveV3.sol'; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; /** * @title PoolTracker contract * @author JustCause * @notice Main point of interaction with JustCause Protocol * This is a proof of concept starter contract for lossless donations * * Aave v3 is used to generate interest for crowdfunding * * PoolTracker contract controls deposit calls to Aave to make * approvals needed only once per token. Calls JustCause Pools for * withdrawals and claims * * Controls Owner/Contributor NFT creation and updates for deposits/withdrawals * * Controls JustCause Pool creation with proxy contracts * * @dev Deposits, withdraws, and claims for Aave Pools * @dev Generate ERC721 token **/ contract PoolTracker is ReentrancyGuard { JustCausePoolAaveV3 baseJCPool; JCDepositorERC721 baseERC721; //contract addresses will point to bool if they exist mapping(address => bool) private isPool; mapping(string => address) private names; mapping(address => uint256) private tvl; mapping(address => uint256) private totalDonated; mapping(address => address[]) private contributors; mapping(address => address[]) private receivers; address[] private verifiedPools; address poolAddr; address wethGatewayAddr; address validator; event AddPool(address pool, string name, address receiver); event AddDeposit(address userAddr, address pool, address asset, uint256 amount); event WithdrawDeposit(address userAddr, address pool, address asset, uint256 amount); event Claim(address userAddr, address receiver, address pool, address asset, uint256 amount); event Test(address[] aaveAccepted, address[] causeAccepted ); /** * @dev Only address that are a pool can be passed to functions marked by this modifier. **/ modifier onlyPools(address _pool){ require(isPool[_pool], "not pool"); _; } /** * @dev Only tokens that are accepted by Aave can be used in JCP creation **/ modifier onlyAcceptedTokens(address[] memory causeAcceptedTokens){ address[] memory aaveAcceptedTokens = IPool(poolAddr).getReservesList(); for(uint8 i = 0; i < causeAcceptedTokens.length; i++){ bool found; for(uint8 j = 0; j < aaveAcceptedTokens.length; j++){ if(causeAcceptedTokens[i] == aaveAcceptedTokens[j]){ found = true; } } require(found, "tokens not approved"); } _; } /** * @dev Only tokens that are accepted by Aave can be passed to functions marked by this modifier. **/ modifier onlyAcceptedToken(address _asset){ address[] memory aaveAcceptedTokens = IPool(poolAddr).getReservesList(); bool found; for(uint8 j = 0; j < aaveAcceptedTokens.length; j++){ if(_asset == aaveAcceptedTokens[j]){ found = true; } } require(found, "token not approved"); _; } /** * @dev Constructor. */ constructor (address _poolAddressesProviderAddr, address _wethGatewayAddr) { validator = msg.sender; baseJCPool = new JustCausePoolAaveV3(); baseERC721 = new JCDepositorERC721(); poolAddr = IPoolAddressesProvider(_poolAddressesProviderAddr).getPool(); wethGatewayAddr = address(_wethGatewayAddr); } /** * @dev Emit AddDeposit * @param _asset The address of the underlying asset of the reserve * @param _amount The amount of supplied assets * @param _pool address of JCP * @param _isETH bool indicating if asset is the base token of network (eth/matic/...) **/ function addDeposit(uint256 _amount, address _asset, address _pool, bool _isETH) onlyPools(_pool) nonReentrant() external payable { tvl[_asset] += _amount; string memory _metaHash = IJustCausePool(_pool).getMetaUri(); address _poolAddr = poolAddr; if(_isETH){ require(IWETHGateway(wethGatewayAddr).getWETHAddress() == _asset, "asset does not match WETHGateway"); require(msg.value > 0, "msg.value cannot be zero"); IWETHGateway(wethGatewayAddr).depositETH{value: msg.value}(_poolAddr, _pool, 0); } else { require(msg.value == 0, "msg.value is not zero"); IERC20 token = IERC20(_asset); require(token.allowance(msg.sender, address(this)) >= _amount, "sender not approved"); token.transferFrom(msg.sender, address(this), _amount); token.approve(_poolAddr, _amount); IPool(_poolAddr).deposit(address(token), _amount, _pool, 0); } IJustCausePool(_pool).deposit(_asset, _amount); bool isFirstDeposit = IJCDepositorERC721(IJustCausePool(_pool).getERC721Address()).addFunds(msg.sender, _amount, block.timestamp, _asset, _metaHash); if(isFirstDeposit){ contributors[msg.sender].push(_pool); } emit AddDeposit(msg.sender, _pool, _asset, _amount); } /** * @dev Emit WithdrawDeposit * @param _asset The address of the underlying asset of the reserve * @param _amount The amount of withdraw assets * @param _pool address of JCP * @param _isETH bool indicating if asset is the base token of network (eth/matic/...) **/ function withdrawDeposit(uint256 _amount, address _asset, address _pool, bool _isETH) external onlyPools(_pool) nonReentrant(){ tvl[_asset] -= _amount; IJCDepositorERC721(IJustCausePool(_pool).getERC721Address()).withdrawFunds(msg.sender, _amount, _asset); IJustCausePool(_pool).withdraw(_asset, _amount, msg.sender, _isETH); emit WithdrawDeposit(msg.sender, _pool, _asset, _amount); } /** * @dev Emit Claim * @param _asset The address of the underlying asset of the reserve * @param _pool address of JCP * @param _isETH bool indicating if asset is the base token of network (eth/matic/...) **/ function claimInterest(address _asset, address _pool, bool _isETH) external onlyPools(_pool) nonReentrant() onlyAcceptedToken(_asset){ uint256 amount = IJustCausePool(_pool).withdrawDonations(_asset, _isETH); totalDonated[_asset] += amount; emit Claim(msg.sender, IJustCausePool(_pool).getRecipient(), _pool, _asset, amount); } /** * @param basePool address of base JCP * @return instance proxy instance of JCP * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. **/ function clone(address basePool) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, basePool)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Emit AddPool * @notice Creates JCP proxy * @param _acceptedTokens List of tokens to be accepted by JCP. * @param _name String name of JCP. * @param _about ipfs hash of pool description of JCP. * @param _picHash ipfs hash of pic of JCP. * @param _metaUri meta info uri for nft of JCP. * @param _receiver address of receiver of JCP donations. **/ function createJCPoolClone( address[] memory _acceptedTokens, string memory _name, string memory _about, string memory _picHash, string memory _metaUri, address _receiver ) external onlyAcceptedTokens(_acceptedTokens){ require(names[_name] == address(0), "pool with name already exists"); address jcpChild = clone(address(baseJCPool)); address erc721Child = clone(address(baseERC721)); bool isVerified; if(msg.sender == validator){ verifiedPools.push(jcpChild); isVerified = true; } IJustCausePool(jcpChild).initialize(_acceptedTokens, _name, _about, _picHash, _metaUri, _receiver, poolAddr, wethGatewayAddr, erc721Child, isVerified); IJCDepositorERC721(erc721Child).initialize(jcpChild); //jCOwnerERC721.createReceiverToken(_receiver, block.timestamp, jcpChild, _metaUri); receivers[_receiver].push(jcpChild); names[_name] = jcpChild; isPool[jcpChild] = true; emit AddPool(jcpChild, _name, _receiver); } /** * @param _asset The address of the underlying asset of the reserve * @return tvl of the protocol for a given asset **/ function getTVL(address _asset) public view returns(uint256){ return tvl[_asset]; } /** * @param _asset The address of the underlying asset of the reserve * @return total claimed donation for a given asset **/ function getTotalDonated(address _asset) public view returns(uint256){ return totalDonated[_asset]; } /** * @return address of ERC721 for depositors, created on deployment **/ function getDepositorERC721Address() public view returns(address){ return address(baseERC721); } /** * @param _user address to check for receiver * @return address[] of pools that a user is a receiver for **/ function getReceiverPools(address _user) public view returns(address[] memory){ return receivers[_user]; } /** * @return address of validator **/ function getValidator() public view returns(address){ return validator; } /** * @param _user The address of the underlying asset of the reserve * @return address[] of pools **/ function getContributions(address _user) public view returns(address[] memory){ return contributors[_user]; } /** * @return address of aave pool **/ function getPoolAddr() public view returns(address){ return poolAddr; } /** * @return address array of aave reserve list **/ function getReservesList() public view returns(address[] memory){ return IPool(poolAddr).getReservesList(); } /** * @return address of base JCP, created on deployment **/ function getBaseJCPoolAddress() public view returns(address){ return address(baseJCPool); } /** * @return list of verified pools **/ function getVerifiedPools() public view returns(address [] memory){ return verifiedPools; } /** * @param _pool address of pool * @return true if pool address exists **/ function checkPool(address _pool) public view returns(bool){ return isPool[_pool]; } /** * @param _name string name of pool * @return pool address of a given pool name **/ function getAddressFromName(string memory _name) external view returns(address){ return names[_name]; } }
Emit AddPool Creates JCP proxy _acceptedTokens List of tokens to be accepted by JCP. _name String name of JCP. _about ipfs hash of pool description of JCP. _picHash ipfs hash of pic of JCP. _metaUri meta info uri for nft of JCP. _receiver address of receiver of JCP donations./
function createJCPoolClone( address[] memory _acceptedTokens, string memory _name, string memory _about, string memory _picHash, string memory _metaUri, address _receiver ) external onlyAcceptedTokens(_acceptedTokens){ require(names[_name] == address(0), "pool with name already exists"); address jcpChild = clone(address(baseJCPool)); address erc721Child = clone(address(baseERC721)); bool isVerified; if(msg.sender == validator){ verifiedPools.push(jcpChild); isVerified = true; } IJustCausePool(jcpChild).initialize(_acceptedTokens, _name, _about, _picHash, _metaUri, _receiver, poolAddr, wethGatewayAddr, erc721Child, isVerified); IJCDepositorERC721(erc721Child).initialize(jcpChild); names[_name] = jcpChild; isPool[jcpChild] = true; emit AddPool(jcpChild, _name, _receiver); }
5,345,738
./full_match/1/0xbFA41711C50aE6F9fd18F062aDb59D1B817B2C1a/sources/home/joshua/Dropbox/Projects/2020_percom/ape_cash/contracts/ApeToken.sol
mint 1800 APE per held ETH to list on Uniswap
function listOnUniswap() public onlyDeveloper onlyBeforeUniswap { timeListed = now; addWhitelist(uniswapEthPair); uint256 ethBalance = address(this).balance; uint256 apeBalance = ethBalance.mul(uniswapApePerEth); _mint(address(this), apeBalance); _approve(address(this), address(router), apeBalance); (uint256 amountToken, uint256 amountEth, uint256 liquidity) = router address(this), apeBalance, apeBalance, ethBalance, address(0), block.timestamp + uint256(5).mul(1 minutes) ); revokeRole(WHITELIST_ROLE, uniswapEthPair); revokeRole(WHITELIST_ROLE, UNISWAP_ROUTER_ADDRESS); addWhitelistFrom(uniswapEthPair); stopPresale(); uniswapPairImpl = IUniswapV2Pair(uniswapEthPair); emit LiquidityAdded(amountToken, amountEth, liquidity); }
9,695,294
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_234(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,453,947
// SPDX-License-Identifier: MIT pragma solidity >=0.7.0; pragma experimental ABIEncoderV2; import "../Interface/IBerry.sol"; /** * @title UserContract * This contracts creates for easy integration to the Berry System * by allowing smart contracts to read data off Berry */ contract UsingBerry { IBerry private berry; /*Constructor*/ /** * @dev the constructor sets the storage address and owner * @param _berry is the BerryMaster address */ constructor(address payable _berry) { berry = IBerry(_berry); } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(uint256 _requestId, uint256 _timestamp) public view returns (uint256) { return berry.retrieveData(_requestId, _timestamp); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to looku p * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint256 _requestId, uint256 _timestamp) public view returns (bool) { return berry.isInDispute(_requestId, _timestamp); } /** * @dev Counts the number of values that have been submited for the request * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint256 _requestId) public view returns (uint256) { return berry.getNewValueCountbyRequestId(_requestId); } /** * @dev Gets the timestamp for the value based on their index * @param _requestId is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint256 _requestId, uint256 _index) public view returns (uint256) { return berry.getTimestampbyRequestIDandIndex(_requestId, _index); } /** * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp * @return value the value retrieved * @return _timestampRetrieved the value's timestamp */ function getCurrentValue(uint256 _requestId) public view returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = berry.getNewValueCountbyRequestId(_requestId); uint256 _time = berry.getTimestampbyRequestIDandIndex(_requestId, _count - 1); uint256 _value = berry.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); } // slither-disable-next-line calls-loop function getIndexForDataBefore(uint256 _requestId, uint256 _timestamp) public view returns (bool found, uint256 index) { uint256 _count = berry.getNewValueCountbyRequestId(_requestId); if (_count > 0) { uint256 middle; uint256 start = 0; uint256 end = _count - 1; uint256 _time; //Checking Boundaries to short-circuit the algorithm _time = berry.getTimestampbyRequestIDandIndex(_requestId, start); if (_time >= _timestamp) return (false, 0); _time = berry.getTimestampbyRequestIDandIndex(_requestId, end); if (_time < _timestamp) return (true, end); //Since the value is within our boundaries, do a binary search while (true) { middle = (end - start) / 2 + 1 + start; _time = berry.getTimestampbyRequestIDandIndex( _requestId, middle ); if (_time < _timestamp) { //get imeadiate next value uint256 _nextTime = berry.getTimestampbyRequestIDandIndex( _requestId, middle + 1 ); if (_nextTime >= _timestamp) { //_time is correct return (true, middle); } else { //look from middle + 1(next value) to end start = middle + 1; } } else { uint256 _prevTime = berry.getTimestampbyRequestIDandIndex( _requestId, middle - 1 ); if (_prevTime < _timestamp) { // _prevtime is correct return (true, middle - 1); } else { //look from start to middle -1(prev value) end = middle - 1; } } //We couldn't found a value //if(middle - 1 == start || middle == _count) return (false, 0); } } return (false, 0); } /** * @dev Allows the user to get the first value for the requestId before the specified timestamp * @param _requestId is the requestId to look up the value for * @param _timestamp before which to search for first verified value * @return _ifRetrieve bool true if it is able to retreive a value, the value, and the value's timestamp * @return _value the value retrieved * @return _timestampRetrieved the value's timestamp */ function getDataBefore(uint256 _requestId, uint256 _timestamp) public view returns ( bool _ifRetrieve, uint256 _value, uint256 _timestampRetrieved ) { (bool _found, uint256 _index) = getIndexForDataBefore(_requestId, _timestamp); if (!_found) return (false, 0, 0); uint256 _time = berry.getTimestampbyRequestIDandIndex(_requestId, _index); _value = berry.retrieveData(_requestId, _time); //If value is diputed it'll return zero if (_value > 0) return (true, _value, _time); return (false, 0, 0); } /** * @return Returns the current reward amount. TODO remove once https://github.com/proxy-io/TellorCore/issues/109 is implemented and deployed. */ function currentReward() external view returns (uint256) { uint256 rewardAccumulated; if (berry.getUintVar(keccak256("height")) > 172800) { rewardAccumulated = 0; } else { rewardAccumulated = 61728395061728390000 / (berry.getUintVar(keccak256("height")) / 43200 + 1); } uint256 tip = berry.getUintVar(keccak256("currentTotalTips")); return (rewardAccumulated + tip) / 5; // each miner } struct value { uint256 timestamp; uint256 value; } /** * @param requestID is the ID for which the function returns the values for. * @param count is the number of last values to return. * @return Returns the last N values for a request ID. */ function getLastNewValues(uint256 requestID, uint256 count) external view returns (value[] memory) { uint256 totalCount = berry.getNewValueCountbyRequestId(requestID); if (count > totalCount) { count = totalCount; } value[] memory values = new value[](count); for (uint256 i = 0; i < count; i++) { uint256 ts = berry.getTimestampbyRequestIDandIndex( requestID, totalCount - i - 1 ); uint256 v = berry.retrieveData(requestID, ts); values[i] = value({timestamp: ts, value: v}); } return values; } /** * @return Returns the contract owner that can do things at will. */ function _deity() external view returns (address) { return berry.getAddressVars(keccak256("_deity")); } /** * @return Returns the contract owner address. */ function _owner() external view returns (address) { return berry.getAddressVars(keccak256("_owner")); } /** * @return Returns the contract pending owner. */ function pending_owner() external view returns (address) { return berry.getAddressVars(keccak256("pending_owner")); } /** * @return Returns the contract address that executes all proxy calls. */ function berryContract() external view returns (address) { return berry.getAddressVars(keccak256("berryContract")); } /** * @param requestID is the ID for which the function returns the total tips. * @return Returns the current tips for a give request ID. */ function totalTip(uint256 requestID) external view returns (uint256) { return berry.getRequestUintVars(requestID, keccak256("totalTip")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the last time when a value was submitted. */ function timeOfLastNewValue() external view returns (uint256) { return berry.getUintVar(keccak256("timeOfLastNewValue")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the total number of requests from user thorugh the addTip function. */ function requestCount() external view returns (uint256) { return berry.getUintVar(keccak256("requestCount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the current block difficulty. * */ function difficulty() external view returns (uint256) { return berry.getUintVar(keccak256("difficulty")); } /** * @return Returns the getUintVar variable named after the function name. * This variable is used to calculate the block difficulty based on * the time diff since the last oracle block. */ function timeTarget() external view returns (uint256) { return berry.getUintVar(keccak256("timeTarget")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the highest api/timestamp PayoutPool. */ function currentTotalTips() external view returns (uint256) { return berry.getUintVar(keccak256("currentTotalTips")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the number of miners who have mined this value so far. */ function slotProgress() external view returns (uint256) { return berry.getUintVar(keccak256("slotProgress")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the cost to dispute a mined value. */ function disputeFee() external view returns (uint256) { return berry.getUintVar(keccak256("disputeFee")); } /** * @return Returns the getUintVar variable named after the function name. */ function disputeCount() external view returns (uint256) { return berry.getUintVar(keccak256("disputeCount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks stake amount required to become a miner. */ function stakeAmount() external view returns (uint256) { return berry.getUintVar(keccak256("stakeAmount")); } /** * @return Returns the getUintVar variable named after the function name. * This variable tracks the number of parties currently staked. */ function stakerCount() external view returns (uint256) { return berry.getUintVar(keccak256("stakerCount")); } }
return Returns the getUintVar variable named after the function name./
function disputeCount() external view returns (uint256) { return berry.getUintVar(keccak256("disputeCount")); }
13,124,241
./full_match/80001/0xF524Cc28CB890F5f0514ABA478E23F0B7BCf8f88/sources/contracts/BnBeanLotteryGame.sol
Set max number of tickets Only callable by owner/
function setMaxNumberTicketsPerBuy( uint256 _maxNumberTicketsPerBuy ) external onlyOwner { require(_maxNumberTicketsPerBuy != 0, "Must be > 0"); maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy; }
5,584,687
./full_match/80001/0x5f46D4F66d82539A7b6231a0A37af81b24809D6c/sources/contracts/abstract/DIDOpt.sol
this function will be set opt data for every public key inputted, this function able to register public key with new token id if not used is detected, this function will be emit 'SettedOptIn' for offchain logging, this function will return tokenId for inheritance action. publicKey is public key want to be set scope data scope is scope data with expected serialized string/
function setOptIn( bytes memory publicKey, string memory scope ) public virtual returns (uint256) { uint256 tokenId = _optTokenId(); require( (publicKey.length == 33 || publicKey.length == 65) && bytes(scope).length > 0 && _canSetOpt(tokenId) == true, "!ALLOWED" ); if (publicKeyUsed[tokenId][publicKey] == false) { publicKeyUsed[tokenId][publicKey] = true; publicKeyTokenList[publicKey].push(tokenId); tokenPublicKeyList[tokenId].push(publicKey); } optData[tokenId][publicKey] = scope; emit SettedOptIn(tokenId, publicKey, scope); return tokenId; }
5,552,821
pragma solidity 0.4.20; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function percent(uint value,uint numerator, uint denominator, uint precision) internal pure returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); uint _quotient = ((_numerator / denominator) + 5) / 10; return (value*_quotient/1000000000000000000); } 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; } } contract TREASURE { /*===================================== = CONTRACT CONFIGURABLES = =====================================*/ // Token Details string public name = "TREASURE"; string public symbol = "TRS"; uint8 constant public decimals = 18; uint256 constant internal tokenPriceInitial = 0.000000001 ether; // Token Price Increment & Decrement By 1Gwei uint256 constant internal tokenPriceIncDec = 0.000000001 ether; // Proof of Stake (Default at 1 Token) uint256 public stakingReq = 1e18; uint256 constant internal magnitude = 2**64; // Dividend/Distribution Percentage uint8 constant internal referralFeePercent = 5; uint8 constant internal dividendFeePercent = 10; uint8 constant internal tradingFundWalletFeePercent = 10; uint8 constant internal communityWalletFeePercent = 10; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal sellingWithdrawBalance_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; mapping(address => string) internal contractTokenHolderAddresses; uint256 internal tokenTotalSupply = 0; uint256 internal calReferralPercentage = 0; uint256 internal calDividendPercentage = 0; uint256 internal calculatedPercentage = 0; uint256 internal soldTokens = 0; uint256 internal tempIncomingEther = 0; uint256 internal tempProfitPerShare = 0; uint256 internal tempIf = 0; uint256 internal tempCalculatedDividends = 0; uint256 internal tempReferall = 0; uint256 internal tempSellingWithdraw = 0; uint256 internal profitPerShare_; // When this is set to true, only ambassadors can purchase tokens bool public onlyAmbassadors = false; // Community Wallet Address address internal constant CommunityWalletAddr = address(0xa6ac94e896fBB8A2c27692e20B301D54D954071E); // Trading Fund Wallet Address address internal constant TradingWalletAddr = address(0x40E68DF89cAa6155812225F12907960608A0B9dd); // Administrator of this contract mapping(bytes32 => bool) public admin; /*================================= = MODIFIERS = =================================*/ // Only people with tokens modifier onlybelievers() { require(myTokens() > 0); _; } // Only people with profits modifier onlyhodler() { require(myDividends(true) > 0); _; } // Only people with sold token modifier onlySelingholder() { require(sellingWithdrawBalance_[msg.sender] > 0); _; } // Admin can do following things: // 1. Change the name of contract. // 2. Change the name of token. // 3. Change the PoS difficulty . // Admin CANNOT do following things: // 1. Take funds out from contract. // 2. Disable withdrawals. // 3. Kill the smart contract. // 4. Change the price of tokens. modifier onlyAdmin() { address _adminAddress = msg.sender; require(admin[keccak256(_adminAddress)]); _; } /*=========================================== = ADMINISTRATOR ONLY FUNCTIONS = ===========================================*/ // Admin can manually disable the ambassador phase function disableInitialStage() onlyAdmin() public { onlyAmbassadors = false; } function setAdmin(bytes32 _identifier, bool _status) onlyAdmin() public { admin[_identifier] = _status; } function setStakingReq(uint256 _tokensAmount) onlyAdmin() public { stakingReq = _tokensAmount; } function setName(string _tokenName) onlyAdmin() public { name = _tokenName; } function setSymbol(string _tokenSymbol) onlyAdmin() public { symbol = _tokenSymbol; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase ( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell ( address indexed customerAddress, uint256 tokensBurned ); event onReinvestment ( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw ( address indexed customerAddress, uint256 ethereumWithdrawn ); event onSellingWithdraw ( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer ( address indexed from, address indexed to, uint256 tokens ); /*======================================= = PUBLIC FUNCTIONS = =======================================*/ function TREASURE() public { // Contract Admin admin[0x7cfa1051b7130edfac6eb71d17a849847cf6b7e7ad0b33fad4e124841e5acfbc] = true; } // Check contract Ethereum Balance function totalEthereumBalance() public view returns(uint) { return this.balance; } // Check tokens total supply function totalSupply() public view returns(uint256) { return tokenTotalSupply; } // Check token balance owned by the caller function myTokens() public view returns(uint256) { address ownerAddress = msg.sender; return tokenBalanceLedger_[ownerAddress]; } // Check sold tokens function getSoldTokens() public view returns(uint256) { return soldTokens; } // Check dividends owned by the caller function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } // Check dividend balance of any single address function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } // Check token balance of any address function balanceOf(address ownerAddress) public view returns(uint256) { return tokenBalanceLedger_[ownerAddress]; ///need to change } // Check Selling Withdraw balance of address function sellingWithdrawBalance() view public returns(uint256) { address _customerAddress = msg.sender; uint256 _sellingWithdraw = (uint256) (sellingWithdrawBalance_[_customerAddress]) ; // Get all balances return _sellingWithdraw; } // Get Buy Price of 1 individual token function sellPrice() public view returns(uint256) { if(tokenTotalSupply == 0){ return tokenPriceInitial - tokenPriceIncDec; } else { uint256 _ethereum = tokensToEthereum_(1e18); return _ethereum - SafeMath.percent(_ethereum,15,100,18); } } // Get Sell Price of 1 individual token function buyPrice() public view returns(uint256) { if(tokenTotalSupply == 0){ return tokenPriceInitial; } else { uint256 _ethereum = tokensToEthereum_(1e18); return _ethereum; } } // Converts all of caller's dividends to tokens function reinvest() onlyhodler() public { address _customerAddress = msg.sender; // Get dividends uint256 _dividends = myDividends(true); // Retrieve Ref. Bonus later in the code // Calculate 10% for distribution uint256 TenPercentForDistribution = SafeMath.percent(_dividends,10,100,18); // Calculate 90% to reinvest into tokens uint256 NinetyPercentToReinvest = SafeMath.percent(_dividends,90,100,18); // Dispatch a buy order with the calculatedPercentage uint256 _tokens = purchaseTokens(NinetyPercentToReinvest, 0x0); // Empty their all dividends beacuse we are reinvesting them payoutsTo_[_customerAddress] += (int256) (SafeMath.sub(_dividends, referralBalance_[_customerAddress]) * magnitude); referralBalance_[_customerAddress] = 0; // Distribute to all users as per holdings profitPerShare_ = SafeMath.add(profitPerShare_, (TenPercentForDistribution * magnitude) / tokenTotalSupply); // Fire Event onReinvestment(_customerAddress, _dividends, _tokens); } // Alias of sell() & withdraw() function function exit() public { // Get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); withdraw(); } // Withdraw all of the callers earnings function withdraw() onlyhodler() public { address _customerAddress = msg.sender; // Calculate 20% of all Dividends and Transfer them to two communities uint256 _dividends = myDividends(true); // get all dividends // Calculate 10% for Trading Wallet uint256 TenPercentForTradingWallet = SafeMath.percent(_dividends,10,100,18); // Calculate 10% for Community Wallet uint256 TenPercentForCommunityWallet= SafeMath.percent(_dividends,10,100,18); // Update Dividend Tracker payoutsTo_[_customerAddress] += (int256) (SafeMath.sub(_dividends, referralBalance_[_customerAddress]) * magnitude); referralBalance_[_customerAddress] = 0; // Delivery Service address(CommunityWalletAddr).transfer(TenPercentForCommunityWallet); // Delivery Service address(TradingWalletAddr).transfer(TenPercentForTradingWallet); // Calculate 80% for transfering it to Customer Address uint256 EightyPercentForCustomer = SafeMath.percent(_dividends,80,100,18); // Delivery Service address(_customerAddress).transfer(EightyPercentForCustomer); // Fire Event onWithdraw(_customerAddress, _dividends); } // Withdraw all sellingWithdraw of the callers earnings function sellingWithdraw() onlySelingholder() public { address customerAddress = msg.sender; uint256 _sellingWithdraw = sellingWithdrawBalance_[customerAddress]; // Empty all sellingWithdraw beacuse we are giving them ETHs sellingWithdrawBalance_[customerAddress] = 0; // Delivery Service address(customerAddress).transfer(_sellingWithdraw); // Fire Event onSellingWithdraw(customerAddress, _sellingWithdraw); } // Sell Tokens // Remember there's a 10% fee for sell function sell(uint256 _amountOfTokens) onlybelievers() public { address customerAddress = msg.sender; // Calculate 10% of tokens and distribute them require(_amountOfTokens <= tokenBalanceLedger_[customerAddress] && _amountOfTokens > 1e18); uint256 _tokens = SafeMath.sub(_amountOfTokens, 1e18); uint256 _ethereum = tokensToEthereum_(_tokens); // Calculate 10% for distribution uint256 TenPercentToDistribute = SafeMath.percent(_ethereum,10,100,18); // Calculate 90% for customer withdraw wallet uint256 NinetyPercentToCustomer = SafeMath.percent(_ethereum,90,100,18); // Burn Sold Tokens tokenTotalSupply = SafeMath.sub(tokenTotalSupply, _tokens); tokenBalanceLedger_[customerAddress] = SafeMath.sub(tokenBalanceLedger_[customerAddress], _tokens); // Substract sold tokens from circulations of tokenTotalSupply soldTokens = SafeMath.sub(soldTokens,_tokens); // Update sellingWithdrawBalance of customer sellingWithdrawBalance_[customerAddress] += NinetyPercentToCustomer; // Update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (TenPercentToDistribute * magnitude)); payoutsTo_[customerAddress] -= _updatedPayouts; // Distribute to all users as per holdings if (tokenTotalSupply > 0) { // Update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (TenPercentToDistribute * magnitude) / tokenTotalSupply); } // Fire Event onTokenSell(customerAddress, _tokens); } // Transfer tokens from the caller to a new holder // Remember there's a 5% fee here for transfer function transfer(address _toAddress, uint256 _amountOfTokens) onlybelievers() public returns(bool) { address customerAddress = msg.sender; // Make sure user have the requested tokens require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[customerAddress] && _amountOfTokens > 1e18); // Calculate 5% of total tokens uint256 FivePercentOfTokens = SafeMath.percent(_amountOfTokens,5,100,18); // Calculate 95% of total tokens uint256 NinetyFivePercentOfTokens = SafeMath.percent(_amountOfTokens,95,100,18); // Burn the fee tokens // Convert ETH to Tokens tokenTotalSupply = SafeMath.sub(tokenTotalSupply,FivePercentOfTokens); // Substract 5% from community of tokens soldTokens = SafeMath.sub(soldTokens, FivePercentOfTokens); // Exchange Tokens tokenBalanceLedger_[customerAddress] = SafeMath.sub(tokenBalanceLedger_[customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], NinetyFivePercentOfTokens) ; // Calculate value of all token to transfer to ETH uint256 FivePercentToDistribute = tokensToEthereum_(FivePercentOfTokens); // Update dividend trackers payoutsTo_[customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * NinetyFivePercentOfTokens); // Distribute to all users as per holdings profitPerShare_ = SafeMath.add(profitPerShare_, (FivePercentToDistribute * magnitude) / tokenTotalSupply); // Fire Event Transfer(customerAddress, _toAddress, NinetyFivePercentOfTokens); return true; } // Function to calculate actual value after Taxes function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { // Calculate 15% for distribution uint256 fifteen_percentToDistribute= SafeMath.percent(_ethereumToSpend,15,100,18); uint256 _dividends = SafeMath.sub(_ethereumToSpend, fifteen_percentToDistribute); uint256 _amountOfTokens = ethereumToTokens_(_dividends); return _amountOfTokens; } // Function to calculate received ETH function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenTotalSupply); uint256 _ethereum = tokensToEthereum_(_tokensToSell); // Calculate 10% for distribution uint256 ten_percentToDistribute= SafeMath.percent(_ethereum,10,100,18); uint256 _dividends = SafeMath.sub(_ethereum, ten_percentToDistribute); return _dividends; } // Convert all incoming ETH to Tokens for the caller and pass down the referral address (if any) function buy(address referredBy) public payable { purchaseTokens(msg.value, referredBy); } // Fallback function to handle ETH that was sent straight to the contract // Unfortunately we cannot use a referral address this way. function() payable public { purchaseTokens(msg.value, 0x0); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 incomingEthereum, address referredBy) internal returns(uint256) { // Datasets address customerAddress = msg.sender; tempIncomingEther = incomingEthereum; // Calculate Percentage for Referral (if any) calReferralPercentage = SafeMath.percent(incomingEthereum,referralFeePercent,100,18); // Calculate Dividend calDividendPercentage = SafeMath.percent(incomingEthereum,dividendFeePercent,100,18); // Calculate remaining amount calculatedPercentage = SafeMath.percent(incomingEthereum,85,100,18); // Token will receive against the sent ETH uint256 _amountOfTokens = ethereumToTokens_(SafeMath.percent(incomingEthereum,85,100,18)); uint256 _dividends = 0; uint256 minOneToken = 1 * (10 ** decimals); require(_amountOfTokens > minOneToken && (SafeMath.add(_amountOfTokens,tokenTotalSupply) > tokenTotalSupply)); // If user referred by a Treasure Key if( // Is this a referred purchase? referredBy != 0x0000000000000000000000000000000000000000 && // No Cheating!!!! referredBy != customerAddress && // Does the referrer have at least X whole tokens? tokenBalanceLedger_[referredBy] >= stakingReq ) { // Give 5 % to Referral User referralBalance_[referredBy] += SafeMath.percent(incomingEthereum,5,100,18); _dividends = calDividendPercentage; } else { // Add the referral bonus back to the global dividend _dividends = SafeMath.add(calDividendPercentage, calReferralPercentage); } // We can't give people infinite ETH if(tokenTotalSupply > 0) { // Add tokens to the pool tokenTotalSupply = SafeMath.add(tokenTotalSupply, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenTotalSupply)); } else { // Add tokens to the pool tokenTotalSupply = _amountOfTokens; } // Update circulating supply & the ledger address for the customer tokenBalanceLedger_[customerAddress] = SafeMath.add(tokenBalanceLedger_[customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[customerAddress] += _updatedPayouts; // Fire Event onTokenPurchase(customerAddress, incomingEthereum, _amountOfTokens, referredBy); // Calculate sold tokens here soldTokens += _amountOfTokens; return _amountOfTokens; } // Calculate token price based on an amount of incoming ETH // It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; // Some conversions occurred to prevent decimal errors or underflows/overflows in solidity code. function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (SqRt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncDec * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncDec)**2)*(tokenTotalSupply**2)) + (2*(tokenPriceIncDec)*_tokenPriceInitial*tokenTotalSupply) ) ), _tokenPriceInitial ) )/(tokenPriceIncDec) )-(tokenTotalSupply); return _tokensReceived; } // Calculate token sell value // It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; // Some conversions occurred to prevent decimal errors or underflows/overflows in solidity code. function tokensToEthereum_(uint256 _tokens) public view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenTotalSupply + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial + (tokenPriceIncDec * (_tokenSupply/1e18)) )-tokenPriceIncDec )*(tokens_ - 1e18) ),(tokenPriceIncDec*((tokens_**2-tokens_)/1e18))/2 )/1e18); return _etherReceived; } // This is where all your gas goes function SqRt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
Calculate token price based on an amount of incoming ETH It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; Some conversions occurred to prevent decimal errors or underflows/overflows in solidity code.
function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (SqRt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncDec * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncDec)**2)*(tokenTotalSupply**2)) + (2*(tokenPriceIncDec)*_tokenPriceInitial*tokenTotalSupply) ) ), _tokenPriceInitial ) )/(tokenPriceIncDec) )-(tokenTotalSupply); return _tokensReceived; }
12,920,317
./full_match/1/0xec39A0Da3F21A3A037Fd72036F8e4e981c62085A/sources/inaaaaa.sol
/ Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { } █ ▀▄ █ █ █ █ █ █ ▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀ ▀▄▄▄▄▀ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ ▀ ▀ */ uint256 amountInWithFee = msg.value.mul(997); uint256 amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
3,185,311
./full_match/43113/0xA938608cb6189309e36dC935F91D5A538bF0B815/sources/contracts/ico.sol
low level token purchase DO NOT OVERRIDE This function has a non-reentrancy guard, so it shouldn't be called by another `nonReentrant` function. beneficiary Recipient of the token purchase/ calculate token amount to be created update state
function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(msg.sender, beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); }
7,109,047