file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.4.19; contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function getBeneficiary() external view returns(address); } contract SanctuaryInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool); /// @dev generate new warrior genes /// @param _heroGenes Genes of warrior that have completed dungeon /// @param _heroLevel Level of the warrior /// @return the genes that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroGenes, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256); } contract PVPInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPProvider() external pure returns (bool); function addTournamentContender(address _owner, uint256[] _tournamentData) external payable; function getTournamentThresholdFee() public view returns(uint256); function addPVPContender(address _owner, uint256 _packedWarrior) external payable; function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256); } contract PVPListenerInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPListener() public pure returns (bool); function getBeneficiary() external view returns(address); function pvpFinished(uint256[] warriorData, uint256 matchingCount) public; function pvpContenderRemoved(uint256 _warriorId) public; function tournamentFinished(uint256[] packedContenders) public; } contract PermissionControll { // This facet controls access to contract that implements it. There are four roles managed here: // // - The Admin: The Admin can reassign admin and issuer roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the CryptoWarriorCore constructor. // // - The Bank: The Bank can withdraw funds from CryptoWarriorCore and its auction and battle contracts, and change admin role. // // - The Issuer: The Issuer can release gen0 warriors to auction. // // / @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public adminAddress; address public bankAddress; address public issuerAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // / @dev Access modifier for Admin-only functionality modifier onlyAdmin(){ require(msg.sender == adminAddress); _; } // / @dev Access modifier for Bank-only functionality modifier onlyBank(){ require(msg.sender == bankAddress); _; } /// @dev Access modifier for Issuer-only functionality modifier onlyIssuer(){ require(msg.sender == issuerAddress); _; } modifier onlyAuthorized(){ require(msg.sender == issuerAddress || msg.sender == adminAddress || msg.sender == bankAddress); _; } // / @dev Assigns a new address to act as the Bank. Only available to the current Bank. // / @param _newBank The address of the new Bank function setBank(address _newBank) external onlyBank { require(_newBank != address(0)); bankAddress = _newBank; } // / @dev Assigns a new address to act as the Admin. Only available to the current Admin. // / @param _newAdmin The address of the new Admin function setAdmin(address _newAdmin) external { require(msg.sender == adminAddress || msg.sender == bankAddress); require(_newAdmin != address(0)); adminAddress = _newAdmin; } // / @dev Assigns a new address to act as the Issuer. Only available to the current Issuer. // / @param _newIssuer The address of the new Issuer function setIssuer(address _newIssuer) external onlyAdmin{ require(_newIssuer != address(0)); issuerAddress = _newIssuer; } /*** Pausable functionality adapted from OpenZeppelin ***/ // / @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused(){ require(!paused); _; } // / @dev Modifier to allow actions only when the contract IS paused modifier whenPaused{ require(paused); _; } // / @dev Called by any "Authorized" role to pause the contract. Used only when // / a bug or exploit is detected and we need to limit damage. function pause() external onlyAuthorized whenNotPaused{ paused = true; } // / @dev Unpauses the smart contract. Can only be called by the Admin. // / @notice This is public rather than external so it can be called by // / derived contracts. function unpause() public onlyAdmin whenPaused{ // can't unpause if contract was upgraded paused = false; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyAdmin whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } } contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner(){ require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner{ if (newOwner != address(0)) { owner = newOwner; } } } contract PausableBattle is Ownable { event PausePVP(bool paused); event PauseTournament(bool paused); bool public pvpPaused = false; bool public tournamentPaused = false; /** PVP */ modifier PVPNotPaused(){ require(!pvpPaused); _; } modifier PVPPaused{ require(pvpPaused); _; } function pausePVP() public onlyOwner PVPNotPaused { pvpPaused = true; PausePVP(true); } function unpausePVP() public onlyOwner PVPPaused { pvpPaused = false; PausePVP(false); } /** Tournament */ modifier TournamentNotPaused(){ require(!tournamentPaused); _; } modifier TournamentPaused{ require(tournamentPaused); _; } function pauseTournament() public onlyOwner TournamentNotPaused { tournamentPaused = true; PauseTournament(true); } function unpauseTournament() public onlyOwner TournamentPaused { tournamentPaused = false; PauseTournament(false); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused(){ require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused{ require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } library CryptoUtils { /* CLASSES */ uint256 internal constant WARRIOR = 0; uint256 internal constant ARCHER = 1; uint256 internal constant MAGE = 2; /* RARITIES */ uint256 internal constant COMMON = 1; uint256 internal constant UNCOMMON = 2; uint256 internal constant RARE = 3; uint256 internal constant MYTHIC = 4; uint256 internal constant LEGENDARY = 5; uint256 internal constant UNIQUE = 6; /* LIMITS */ uint256 internal constant CLASS_MECHANICS_MAX = 3; uint256 internal constant RARITY_MAX = 6; /*@dev range used for rarity chance computation */ uint256 internal constant RARITY_CHANCE_RANGE = 10000000; uint256 internal constant POINTS_TO_LEVEL = 10; /* ATTRIBUTE MASKS */ /*@dev range 0-9999 */ uint256 internal constant UNIQUE_MASK_0 = 1; /*@dev range 0-9 */ uint256 internal constant RARITY_MASK_1 = UNIQUE_MASK_0 * 10000; /*@dev range 0-999 */ uint256 internal constant CLASS_VIEW_MASK_2 = RARITY_MASK_1 * 10; /*@dev range 0-999 */ uint256 internal constant BODY_COLOR_MASK_3 = CLASS_VIEW_MASK_2 * 1000; /*@dev range 0-999 */ uint256 internal constant EYES_MASK_4 = BODY_COLOR_MASK_3 * 1000; /*@dev range 0-999 */ uint256 internal constant MOUTH_MASK_5 = EYES_MASK_4 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_MASK_6 = MOUTH_MASK_5 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_COLOR_MASK_7 = HEIR_MASK_6 * 1000; /*@dev range 0-999 */ uint256 internal constant ARMOR_MASK_8 = HEIR_COLOR_MASK_7 * 1000; /*@dev range 0-999 */ uint256 internal constant WEAPON_MASK_9 = ARMOR_MASK_8 * 1000; /*@dev range 0-999 */ uint256 internal constant HAT_MASK_10 = WEAPON_MASK_9 * 1000; /*@dev range 0-99 */ uint256 internal constant RUNES_MASK_11 = HAT_MASK_10 * 1000; /*@dev range 0-99 */ uint256 internal constant WINGS_MASK_12 = RUNES_MASK_11 * 100; /*@dev range 0-99 */ uint256 internal constant PET_MASK_13 = WINGS_MASK_12 * 100; /*@dev range 0-99 */ uint256 internal constant BORDER_MASK_14 = PET_MASK_13 * 100; /*@dev range 0-99 */ uint256 internal constant BACKGROUND_MASK_15 = BORDER_MASK_14 * 100; /*@dev range 0-99 */ uint256 internal constant INTELLIGENCE_MASK_16 = BACKGROUND_MASK_15 * 100; /*@dev range 0-99 */ uint256 internal constant AGILITY_MASK_17 = INTELLIGENCE_MASK_16 * 100; /*@dev range 0-99 */ uint256 internal constant STRENGTH_MASK_18 = AGILITY_MASK_17 * 100; /*@dev range 0-9 */ uint256 internal constant CLASS_MECH_MASK_19 = STRENGTH_MASK_18 * 100; /*@dev range 0-999 */ uint256 internal constant RARITY_BONUS_MASK_20 = CLASS_MECH_MASK_19 * 10; /*@dev range 0-9 */ uint256 internal constant SPECIALITY_MASK_21 = RARITY_BONUS_MASK_20 * 1000; /*@dev range 0-99 */ uint256 internal constant DAMAGE_MASK_22 = SPECIALITY_MASK_21 * 10; /*@dev range 0-99 */ uint256 internal constant AURA_MASK_23 = DAMAGE_MASK_22 * 100; /*@dev 20 decimals left */ uint256 internal constant BASE_MASK_24 = AURA_MASK_23 * 100; /* SPECIAL PERKS */ uint256 internal constant MINER_PERK = 1; /* PARAM INDEXES */ uint256 internal constant BODY_COLOR_MAX_INDEX_0 = 0; uint256 internal constant EYES_MAX_INDEX_1 = 1; uint256 internal constant MOUTH_MAX_2 = 2; uint256 internal constant HAIR_MAX_3 = 3; uint256 internal constant HEIR_COLOR_MAX_4 = 4; uint256 internal constant ARMOR_MAX_5 = 5; uint256 internal constant WEAPON_MAX_6 = 6; uint256 internal constant HAT_MAX_7 = 7; uint256 internal constant RUNES_MAX_8 = 8; uint256 internal constant WINGS_MAX_9 = 9; uint256 internal constant PET_MAX_10 = 10; uint256 internal constant BORDER_MAX_11 = 11; uint256 internal constant BACKGROUND_MAX_12 = 12; uint256 internal constant UNIQUE_INDEX_13 = 13; uint256 internal constant LEGENDARY_INDEX_14 = 14; uint256 internal constant MYTHIC_INDEX_15 = 15; uint256 internal constant RARE_INDEX_16 = 16; uint256 internal constant UNCOMMON_INDEX_17 = 17; uint256 internal constant UNIQUE_TOTAL_INDEX_18 = 18; /* PACK PVP DATA LOGIC */ //pvp data uint256 internal constant CLASS_PACK_0 = 1; uint256 internal constant RARITY_BONUS_PACK_1 = CLASS_PACK_0 * 10; uint256 internal constant RARITY_PACK_2 = RARITY_BONUS_PACK_1 * 1000; uint256 internal constant EXPERIENCE_PACK_3 = RARITY_PACK_2 * 10; uint256 internal constant INTELLIGENCE_PACK_4 = EXPERIENCE_PACK_3 * 1000; uint256 internal constant AGILITY_PACK_5 = INTELLIGENCE_PACK_4 * 100; uint256 internal constant STRENGTH_PACK_6 = AGILITY_PACK_5 * 100; uint256 internal constant BASE_DAMAGE_PACK_7 = STRENGTH_PACK_6 * 100; uint256 internal constant PET_PACK_8 = BASE_DAMAGE_PACK_7 * 100; uint256 internal constant AURA_PACK_9 = PET_PACK_8 * 100; uint256 internal constant WARRIOR_ID_PACK_10 = AURA_PACK_9 * 100; uint256 internal constant PVP_CYCLE_PACK_11 = WARRIOR_ID_PACK_10 * 10**10; uint256 internal constant RATING_PACK_12 = PVP_CYCLE_PACK_11 * 10**10; uint256 internal constant PVP_BASE_PACK_13 = RATING_PACK_12 * 10**10;//NB rating must be at the END! //tournament data uint256 internal constant HP_PACK_0 = 1; uint256 internal constant DAMAGE_PACK_1 = HP_PACK_0 * 10**12; uint256 internal constant ARMOR_PACK_2 = DAMAGE_PACK_1 * 10**12; uint256 internal constant DODGE_PACK_3 = ARMOR_PACK_2 * 10**12; uint256 internal constant PENETRATION_PACK_4 = DODGE_PACK_3 * 10**12; uint256 internal constant COMBINE_BASE_PACK_5 = PENETRATION_PACK_4 * 10**12; /* MISC CONSTANTS */ uint256 internal constant MAX_ID_SIZE = 10000000000; int256 internal constant PRECISION = 1000000; uint256 internal constant BATTLES_PER_CONTENDER = 10;//10x100 uint256 internal constant BATTLES_PER_CONTENDER_SUM = BATTLES_PER_CONTENDER * 100;//10x100 uint256 internal constant LEVEL_BONUSES = 98898174676155504541373431282523211917151413121110; //ucommon bonuses uint256 internal constant BONUS_NONE = 0; uint256 internal constant BONUS_HP = 1; uint256 internal constant BONUS_ARMOR = 2; uint256 internal constant BONUS_CRIT_CHANCE = 3; uint256 internal constant BONUS_CRIT_MULT = 4; uint256 internal constant BONUS_PENETRATION = 5; //rare bonuses uint256 internal constant BONUS_STR = 6; uint256 internal constant BONUS_AGI = 7; uint256 internal constant BONUS_INT = 8; uint256 internal constant BONUS_DAMAGE = 9; //bonus value database, uint256 internal constant BONUS_DATA = 16060606140107152000; //pets database uint256 internal constant PETS_DATA = 287164235573728325842459981692000; uint256 internal constant PET_AURA = 2; uint256 internal constant PET_PARAM_1 = 1; uint256 internal constant PET_PARAM_2 = 0; /* GETTERS */ function getUniqueValue(uint256 identity) internal pure returns(uint256){ return identity % RARITY_MASK_1; } function getRarityValue(uint256 identity) internal pure returns(uint256){ return (identity % CLASS_VIEW_MASK_2) / RARITY_MASK_1; } function getClassViewValue(uint256 identity) internal pure returns(uint256){ return (identity % BODY_COLOR_MASK_3) / CLASS_VIEW_MASK_2; } function getBodyColorValue(uint256 identity) internal pure returns(uint256){ return (identity % EYES_MASK_4) / BODY_COLOR_MASK_3; } function getEyesValue(uint256 identity) internal pure returns(uint256){ return (identity % MOUTH_MASK_5) / EYES_MASK_4; } function getMouthValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_MASK_6) / MOUTH_MASK_5; } function getHairValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_COLOR_MASK_7) / HEIR_MASK_6; } function getHairColorValue(uint256 identity) internal pure returns(uint256){ return (identity % ARMOR_MASK_8) / HEIR_COLOR_MASK_7; } function getArmorValue(uint256 identity) internal pure returns(uint256){ return (identity % WEAPON_MASK_9) / ARMOR_MASK_8; } function getWeaponValue(uint256 identity) internal pure returns(uint256){ return (identity % HAT_MASK_10) / WEAPON_MASK_9; } function getHatValue(uint256 identity) internal pure returns(uint256){ return (identity % RUNES_MASK_11) / HAT_MASK_10; } function getRunesValue(uint256 identity) internal pure returns(uint256){ return (identity % WINGS_MASK_12) / RUNES_MASK_11; } function getWingsValue(uint256 identity) internal pure returns(uint256){ return (identity % PET_MASK_13) / WINGS_MASK_12; } function getPetValue(uint256 identity) internal pure returns(uint256){ return (identity % BORDER_MASK_14) / PET_MASK_13; } function getBorderValue(uint256 identity) internal pure returns(uint256){ return (identity % BACKGROUND_MASK_15) / BORDER_MASK_14; } function getBackgroundValue(uint256 identity) internal pure returns(uint256){ return (identity % INTELLIGENCE_MASK_16) / BACKGROUND_MASK_15; } function getIntelligenceValue(uint256 identity) internal pure returns(uint256){ return (identity % AGILITY_MASK_17) / INTELLIGENCE_MASK_16; } function getAgilityValue(uint256 identity) internal pure returns(uint256){ return ((identity % STRENGTH_MASK_18) / AGILITY_MASK_17); } function getStrengthValue(uint256 identity) internal pure returns(uint256){ return ((identity % CLASS_MECH_MASK_19) / STRENGTH_MASK_18); } function getClassMechValue(uint256 identity) internal pure returns(uint256){ return (identity % RARITY_BONUS_MASK_20) / CLASS_MECH_MASK_19; } function getRarityBonusValue(uint256 identity) internal pure returns(uint256){ return (identity % SPECIALITY_MASK_21) / RARITY_BONUS_MASK_20; } function getSpecialityValue(uint256 identity) internal pure returns(uint256){ return (identity % DAMAGE_MASK_22) / SPECIALITY_MASK_21; } function getDamageValue(uint256 identity) internal pure returns(uint256){ return (identity % AURA_MASK_23) / DAMAGE_MASK_22; } function getAuraValue(uint256 identity) internal pure returns(uint256){ return ((identity % BASE_MASK_24) / AURA_MASK_23); } /* SETTERS */ function _setUniqueValue0(uint256 value) internal pure returns(uint256){ require(value < RARITY_MASK_1); return value * UNIQUE_MASK_0; } function _setRarityValue1(uint256 value) internal pure returns(uint256){ require(value < (CLASS_VIEW_MASK_2 / RARITY_MASK_1)); return value * RARITY_MASK_1; } function _setClassViewValue2(uint256 value) internal pure returns(uint256){ require(value < (BODY_COLOR_MASK_3 / CLASS_VIEW_MASK_2)); return value * CLASS_VIEW_MASK_2; } function _setBodyColorValue3(uint256 value) internal pure returns(uint256){ require(value < (EYES_MASK_4 / BODY_COLOR_MASK_3)); return value * BODY_COLOR_MASK_3; } function _setEyesValue4(uint256 value) internal pure returns(uint256){ require(value < (MOUTH_MASK_5 / EYES_MASK_4)); return value * EYES_MASK_4; } function _setMouthValue5(uint256 value) internal pure returns(uint256){ require(value < (HEIR_MASK_6 / MOUTH_MASK_5)); return value * MOUTH_MASK_5; } function _setHairValue6(uint256 value) internal pure returns(uint256){ require(value < (HEIR_COLOR_MASK_7 / HEIR_MASK_6)); return value * HEIR_MASK_6; } function _setHairColorValue7(uint256 value) internal pure returns(uint256){ require(value < (ARMOR_MASK_8 / HEIR_COLOR_MASK_7)); return value * HEIR_COLOR_MASK_7; } function _setArmorValue8(uint256 value) internal pure returns(uint256){ require(value < (WEAPON_MASK_9 / ARMOR_MASK_8)); return value * ARMOR_MASK_8; } function _setWeaponValue9(uint256 value) internal pure returns(uint256){ require(value < (HAT_MASK_10 / WEAPON_MASK_9)); return value * WEAPON_MASK_9; } function _setHatValue10(uint256 value) internal pure returns(uint256){ require(value < (RUNES_MASK_11 / HAT_MASK_10)); return value * HAT_MASK_10; } function _setRunesValue11(uint256 value) internal pure returns(uint256){ require(value < (WINGS_MASK_12 / RUNES_MASK_11)); return value * RUNES_MASK_11; } function _setWingsValue12(uint256 value) internal pure returns(uint256){ require(value < (PET_MASK_13 / WINGS_MASK_12)); return value * WINGS_MASK_12; } function _setPetValue13(uint256 value) internal pure returns(uint256){ require(value < (BORDER_MASK_14 / PET_MASK_13)); return value * PET_MASK_13; } function _setBorderValue14(uint256 value) internal pure returns(uint256){ require(value < (BACKGROUND_MASK_15 / BORDER_MASK_14)); return value * BORDER_MASK_14; } function _setBackgroundValue15(uint256 value) internal pure returns(uint256){ require(value < (INTELLIGENCE_MASK_16 / BACKGROUND_MASK_15)); return value * BACKGROUND_MASK_15; } function _setIntelligenceValue16(uint256 value) internal pure returns(uint256){ require(value < (AGILITY_MASK_17 / INTELLIGENCE_MASK_16)); return value * INTELLIGENCE_MASK_16; } function _setAgilityValue17(uint256 value) internal pure returns(uint256){ require(value < (STRENGTH_MASK_18 / AGILITY_MASK_17)); return value * AGILITY_MASK_17; } function _setStrengthValue18(uint256 value) internal pure returns(uint256){ require(value < (CLASS_MECH_MASK_19 / STRENGTH_MASK_18)); return value * STRENGTH_MASK_18; } function _setClassMechValue19(uint256 value) internal pure returns(uint256){ require(value < (RARITY_BONUS_MASK_20 / CLASS_MECH_MASK_19)); return value * CLASS_MECH_MASK_19; } function _setRarityBonusValue20(uint256 value) internal pure returns(uint256){ require(value < (SPECIALITY_MASK_21 / RARITY_BONUS_MASK_20)); return value * RARITY_BONUS_MASK_20; } function _setSpecialityValue21(uint256 value) internal pure returns(uint256){ require(value < (DAMAGE_MASK_22 / SPECIALITY_MASK_21)); return value * SPECIALITY_MASK_21; } function _setDamgeValue22(uint256 value) internal pure returns(uint256){ require(value < (AURA_MASK_23 / DAMAGE_MASK_22)); return value * DAMAGE_MASK_22; } function _setAuraValue23(uint256 value) internal pure returns(uint256){ require(value < (BASE_MASK_24 / AURA_MASK_23)); return value * AURA_MASK_23; } /* WARRIOR IDENTITY GENERATION */ function _computeRunes(uint256 _rarity) internal pure returns (uint256){ return _rarity > UNCOMMON ? _rarity - UNCOMMON : 0;// 1 + _random(0, max, hash, WINGS_MASK_12, RUNES_MASK_11) : 0; } function _computeWings(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > RARE ? 1 + _random(0, max, hash, PET_MASK_13, WINGS_MASK_12) : 0; } function _computePet(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > MYTHIC ? 1 + _random(0, max, hash, BORDER_MASK_14, PET_MASK_13) : 0; } function _computeBorder(uint256 _rarity) internal pure returns (uint256){ return _rarity >= COMMON ? _rarity - 1 : 0; } function _computeBackground(uint256 _rarity) internal pure returns (uint256){ return _rarity; } function _unpackPetData(uint256 index) internal pure returns(uint256){ return (PETS_DATA % (1000 ** (index + 1)) / (1000 ** index)); } function _getPetBonus1(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_1 + 1)) / (10 ** PET_PARAM_1)); } function _getPetBonus2(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_2 + 1)) / (10 ** PET_PARAM_2)); } function _getPetAura(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_AURA + 1)) / (10 ** PET_AURA)); } function _getBattleBonus(uint256 _setBonusIndex, uint256 _currentBonusIndex, uint256 _petData, uint256 _warriorAuras, uint256 _petAuras) internal pure returns(int256) { int256 bonus = 0; if (_setBonusIndex == _currentBonusIndex) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } //add pet bonuses if (_setBonusIndex == _getPetBonus1(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } if (_setBonusIndex == _getPetBonus2(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add warrior aura bonuses if (isAuraSet(_warriorAuras, uint8(_setBonusIndex))) {//warriors receive half bonuses from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add pet aura bonuses if (isAuraSet(_petAuras, uint8(_setBonusIndex))) {//pets receive full bonues from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } return bonus; } function _computeRarityBonus(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity == UNCOMMON) { return 1 + _random(0, BONUS_PENETRATION, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity == RARE) { return 1 + _random(BONUS_PENETRATION, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } return BONUS_NONE; } function _computeAura(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, BASE_MASK_24, AURA_MASK_23); } return BONUS_NONE; } function _computeRarity(uint256 _reward, uint256 _unique, uint256 _legendary, uint256 _mythic, uint256 _rare, uint256 _uncommon) internal pure returns(uint256){ uint256 range = _unique + _legendary + _mythic + _rare + _uncommon; if (_reward >= range) return COMMON; // common if (_reward >= (range = (range - _uncommon))) return UNCOMMON; if (_reward >= (range = (range - _rare))) return RARE; if (_reward >= (range = (range - _mythic))) return MYTHIC; if (_reward >= (range = (range - _legendary))) return LEGENDARY; if (_reward < range) return UNIQUE; return COMMON; } function _computeUniqueness(uint256 _rarity, uint256 nextUnique) internal pure returns (uint256){ return _rarity == UNIQUE ? nextUnique : 0; } /* identity packing */ /* @returns bonus value which depends on speciality value, * if speciality == 1 (miner), then bonus value will be equal 4, * otherwise 1 */ function _getBonus(uint256 identity) internal pure returns(uint256){ return getSpecialityValue(identity) == MINER_PERK ? 4 : 1; } function _computeAndSetBaseParameters16_18_22(uint256 _hash) internal pure returns (uint256, uint256){ uint256 identity = 0; uint256 damage = 35 + _random(0, 21, _hash, AURA_MASK_23, DAMAGE_MASK_22); uint256 strength = 45 + _random(0, 26, _hash, CLASS_MECH_MASK_19, STRENGTH_MASK_18); uint256 agility = 15 + (125 - damage - strength); uint256 intelligence = 155 - strength - agility - damage; (strength, agility, intelligence) = _shuffleParams(strength, agility, intelligence, _hash); identity += _setStrengthValue18(strength); identity += _setAgilityValue17(agility); identity += _setIntelligenceValue16(intelligence); identity += _setDamgeValue22(damage); uint256 classMech = strength > agility ? (strength > intelligence ? WARRIOR : MAGE) : (agility > intelligence ? ARCHER : MAGE); return (identity, classMech); } function _shuffleParams(uint256 param1, uint256 param2, uint256 param3, uint256 _hash) internal pure returns(uint256, uint256, uint256) { uint256 temp = param1; if (_hash % 2 == 0) { temp = param1; param1 = param2; param2 = temp; } if ((_hash / 10 % 2) == 0) { temp = param2; param2 = param3; param3 = temp; } if ((_hash / 100 % 2) == 0) { temp = param1; param1 = param2; param2 = temp; } return (param1, param2, param3); } /* RANDOM */ function _random(uint256 _min, uint256 _max, uint256 _hash, uint256 _reminder, uint256 _devider) internal pure returns (uint256){ return ((_hash % _reminder) / _devider) % (_max - _min) + _min; } function _random(uint256 _min, uint256 _max, uint256 _hash) internal pure returns (uint256){ return _hash % (_max - _min) + _min; } function _getTargetBlock(uint256 _targetBlock) internal view returns(uint256){ uint256 currentBlock = block.number; uint256 target = currentBlock - (currentBlock % 256) + (_targetBlock % 256); if (target >= currentBlock) { return (target - 256); } return target; } function _getMaxRarityChance() internal pure returns(uint256){ return RARITY_CHANCE_RANGE; } function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 specialPerc, uint32[19] memory params) internal view returns (uint256) { _targetBlock = _getTargetBlock(_targetBlock); uint256 identity; uint256 hash = uint256(keccak256(block.blockhash(_targetBlock), _heroIdentity, block.coinbase, block.difficulty)); //0 _heroLevel produces warriors of COMMON rarity uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE : _random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000 uint256 rarity = _computeRarity(rarityChance, params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]); uint256 classMech; // start (identity, classMech) = _computeAndSetBaseParameters16_18_22(hash); identity += _setUniqueValue0(_computeUniqueness(rarity, params[UNIQUE_TOTAL_INDEX_18] + 1)); identity += _setRarityValue1(rarity); identity += _setClassViewValue2(classMech); // 1 to 1 with classMech identity += _setBodyColorValue3(1 + _random(0, params[BODY_COLOR_MAX_INDEX_0], hash, EYES_MASK_4, BODY_COLOR_MASK_3)); identity += _setEyesValue4(1 + _random(0, params[EYES_MAX_INDEX_1], hash, MOUTH_MASK_5, EYES_MASK_4)); identity += _setMouthValue5(1 + _random(0, params[MOUTH_MAX_2], hash, HEIR_MASK_6, MOUTH_MASK_5)); identity += _setHairValue6(1 + _random(0, params[HAIR_MAX_3], hash, HEIR_COLOR_MASK_7, HEIR_MASK_6)); identity += _setHairColorValue7(1 + _random(0, params[HEIR_COLOR_MAX_4], hash, ARMOR_MASK_8, HEIR_COLOR_MASK_7)); identity += _setArmorValue8(1 + _random(0, params[ARMOR_MAX_5], hash, WEAPON_MASK_9, ARMOR_MASK_8)); identity += _setWeaponValue9(1 + _random(0, params[WEAPON_MAX_6], hash, HAT_MASK_10, WEAPON_MASK_9)); identity += _setHatValue10(_random(0, params[HAT_MAX_7], hash, RUNES_MASK_11, HAT_MASK_10));//removed +1 identity += _setRunesValue11(_computeRunes(rarity)); identity += _setWingsValue12(_computeWings(rarity, params[WINGS_MAX_9], hash)); identity += _setPetValue13(_computePet(rarity, params[PET_MAX_10], hash)); identity += _setBorderValue14(_computeBorder(rarity)); // 1 to 1 with rarity identity += _setBackgroundValue15(_computeBackground(rarity)); // 1 to 1 with rarity identity += _setClassMechValue19(classMech); identity += _setRarityBonusValue20(_computeRarityBonus(rarity, hash)); identity += _setSpecialityValue21(specialPerc); // currently only miner (1) identity += _setAuraValue23(_computeAura(rarity, hash)); // end return identity; } function _changeParameter(uint256 _paramIndex, uint32 _value, uint32[19] storage parameters) internal { //we can change only view parameters, and unique count in max range <= 100 require(_paramIndex >= BODY_COLOR_MAX_INDEX_0 && _paramIndex <= UNIQUE_INDEX_13); //we can NOT set pet, border and background values, //those values have special logic behind them require( _paramIndex != RUNES_MAX_8 && _paramIndex != PET_MAX_10 && _paramIndex != BORDER_MAX_11 && _paramIndex != BACKGROUND_MAX_12 ); //value of bodyColor, eyes, mouth, hair, hairColor, armor, weapon, hat must be < 1000 require(_paramIndex > HAT_MAX_7 || _value < 1000); //value of wings, must be < 100 require(_paramIndex > BACKGROUND_MAX_12 || _value < 100); //check that max total number of UNIQUE warriors that we can emit is not > 100 require(_paramIndex != UNIQUE_INDEX_13 || (_value + parameters[UNIQUE_TOTAL_INDEX_18]) <= 100); parameters[_paramIndex] = _value; } function _recordWarriorData(uint256 identity, uint32[19] storage parameters) internal { uint256 rarity = getRarityValue(identity); if (rarity == UNCOMMON) { // uncommon parameters[UNCOMMON_INDEX_17]--; return; } if (rarity == RARE) { // rare parameters[RARE_INDEX_16]--; return; } if (rarity == MYTHIC) { // mythic parameters[MYTHIC_INDEX_15]--; return; } if (rarity == LEGENDARY) { // legendary parameters[LEGENDARY_INDEX_14]--; return; } if (rarity == UNIQUE) { // unique parameters[UNIQUE_INDEX_13]--; parameters[UNIQUE_TOTAL_INDEX_18] ++; return; } } function _validateIdentity(uint256 _identity, uint32[19] memory params) internal pure returns(bool){ uint256 rarity = getRarityValue(_identity); require(rarity <= UNIQUE); require( rarity <= COMMON ||//common (rarity == UNCOMMON && params[UNCOMMON_INDEX_17] > 0) ||//uncommon (rarity == RARE && params[RARE_INDEX_16] > 0) ||//rare (rarity == MYTHIC && params[MYTHIC_INDEX_15] > 0) ||//mythic (rarity == LEGENDARY && params[LEGENDARY_INDEX_14] > 0) ||//legendary (rarity == UNIQUE && params[UNIQUE_INDEX_13] > 0)//unique ); require(rarity != UNIQUE || getUniqueValue(_identity) > params[UNIQUE_TOTAL_INDEX_18]); //check battle parameters require( getStrengthValue(_identity) < 100 && getAgilityValue(_identity) < 100 && getIntelligenceValue(_identity) < 100 && getDamageValue(_identity) <= 55 ); require(getClassMechValue(_identity) <= MAGE); require(getClassMechValue(_identity) == getClassViewValue(_identity)); require(getSpecialityValue(_identity) <= MINER_PERK); require(getRarityBonusValue(_identity) <= BONUS_DAMAGE); require(getAuraValue(_identity) <= BONUS_DAMAGE); //check view require(getBodyColorValue(_identity) <= params[BODY_COLOR_MAX_INDEX_0]); require(getEyesValue(_identity) <= params[EYES_MAX_INDEX_1]); require(getMouthValue(_identity) <= params[MOUTH_MAX_2]); require(getHairValue(_identity) <= params[HAIR_MAX_3]); require(getHairColorValue(_identity) <= params[HEIR_COLOR_MAX_4]); require(getArmorValue(_identity) <= params[ARMOR_MAX_5]); require(getWeaponValue(_identity) <= params[WEAPON_MAX_6]); require(getHatValue(_identity) <= params[HAT_MAX_7]); require(getRunesValue(_identity) <= params[RUNES_MAX_8]); require(getWingsValue(_identity) <= params[WINGS_MAX_9]); require(getPetValue(_identity) <= params[PET_MAX_10]); require(getBorderValue(_identity) <= params[BORDER_MAX_11]); require(getBackgroundValue(_identity) <= params[BACKGROUND_MAX_12]); return true; } /* UNPACK METHODS */ //common function _unpackClassValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / CLASS_PACK_0); } function _unpackRarityBonusValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / RARITY_BONUS_PACK_1); } function _unpackRarityValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % EXPERIENCE_PACK_3 / RARITY_PACK_2); } function _unpackExpValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4 / EXPERIENCE_PACK_3); } function _unpackLevelValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4) / (EXPERIENCE_PACK_3 * POINTS_TO_LEVEL); } function _unpackIntelligenceValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % AGILITY_PACK_5 / INTELLIGENCE_PACK_4); } function _unpackAgilityValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % STRENGTH_PACK_6 / AGILITY_PACK_5); } function _unpackStrengthValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % BASE_DAMAGE_PACK_7 / STRENGTH_PACK_6); } function _unpackBaseDamageValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % PET_PACK_8 / BASE_DAMAGE_PACK_7); } function _unpackPetValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % AURA_PACK_9 / PET_PACK_8); } function _unpackAuraValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % WARRIOR_ID_PACK_10 / AURA_PACK_9); } // //pvp unpack function _unpackIdValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_CYCLE_PACK_11 / WARRIOR_ID_PACK_10); } function _unpackCycleValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RATING_PACK_12 / PVP_CYCLE_PACK_11); } function _unpackRatingValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_BASE_PACK_13 / RATING_PACK_12); } //max cycle skip value cant be more than 1000000000 function _changeCycleValue(uint256 packedValue, uint256 newValue) internal pure returns(uint256){ newValue = newValue > 1000000000 ? 1000000000 : newValue; return packedValue - (_unpackCycleValue(packedValue) * PVP_CYCLE_PACK_11) + newValue * PVP_CYCLE_PACK_11; } function _packWarriorCommonData(uint256 _identity, uint256 _experience) internal pure returns(uint256){ uint256 packedData = 0; packedData += getClassMechValue(_identity) * CLASS_PACK_0; packedData += getRarityBonusValue(_identity) * RARITY_BONUS_PACK_1; packedData += getRarityValue(_identity) * RARITY_PACK_2; packedData += _experience * EXPERIENCE_PACK_3; packedData += getIntelligenceValue(_identity) * INTELLIGENCE_PACK_4; packedData += getAgilityValue(_identity) * AGILITY_PACK_5; packedData += getStrengthValue(_identity) * STRENGTH_PACK_6; packedData += getDamageValue(_identity) * BASE_DAMAGE_PACK_7; packedData += getPetValue(_identity) * PET_PACK_8; return packedData; } function _packWarriorPvpData(uint256 _identity, uint256 _rating, uint256 _pvpCycle, uint256 _warriorId, uint256 _experience) internal pure returns(uint256){ uint256 packedData = _packWarriorCommonData(_identity, _experience); packedData += _warriorId * WARRIOR_ID_PACK_10; packedData += _pvpCycle * PVP_CYCLE_PACK_11; //rating MUST have most significant value! packedData += _rating * RATING_PACK_12; return packedData; } /* TOURNAMENT BATTLES */ function _packWarriorIds(uint256[] memory packedWarriors) internal pure returns(uint256){ uint256 packedIds = 0; uint256 length = packedWarriors.length; for(uint256 i = 0; i < length; i ++) { packedIds += (MAX_ID_SIZE ** i) * _unpackIdValue(packedWarriors[i]); } return packedIds; } function _unpackWarriorId(uint256 packedIds, uint256 index) internal pure returns(uint256){ return (packedIds % (MAX_ID_SIZE ** (index + 1)) / (MAX_ID_SIZE ** index)); } function _packCombinedParams(int256 hp, int256 damage, int256 armor, int256 dodge, int256 penetration) internal pure returns(uint256) { uint256 combinedWarrior = 0; combinedWarrior += uint256(hp) * HP_PACK_0; combinedWarrior += uint256(damage) * DAMAGE_PACK_1; combinedWarrior += uint256(armor) * ARMOR_PACK_2; combinedWarrior += uint256(dodge) * DODGE_PACK_3; combinedWarrior += uint256(penetration) * PENETRATION_PACK_4; return combinedWarrior; } function _unpackProtectionParams(uint256 combinedWarrior) internal pure returns (int256 hp, int256 armor, int256 dodge){ hp = int256(combinedWarrior % DAMAGE_PACK_1 / HP_PACK_0); armor = int256(combinedWarrior % DODGE_PACK_3 / ARMOR_PACK_2); dodge = int256(combinedWarrior % PENETRATION_PACK_4 / DODGE_PACK_3); } function _unpackAttackParams(uint256 combinedWarrior) internal pure returns(int256 damage, int256 penetration) { damage = int256(combinedWarrior % ARMOR_PACK_2 / DAMAGE_PACK_1); penetration = int256(combinedWarrior % COMBINE_BASE_PACK_5 / PENETRATION_PACK_4); } function _combineWarriors(uint256[] memory packedWarriors) internal pure returns (uint256) { int256 hp; int256 damage; int256 armor; int256 dodge; int256 penetration; (hp, damage, armor, dodge, penetration) = _computeCombinedParams(packedWarriors); return _packCombinedParams(hp, damage, armor, dodge, penetration); } function _computeCombinedParams(uint256[] memory packedWarriors) internal pure returns (int256 totalHp, int256 totalDamage, int256 maxArmor, int256 maxDodge, int256 maxPenetration){ uint256 length = packedWarriors.length; int256 hp; int256 armor; int256 dodge; int256 penetration; uint256 warriorAuras; uint256 petAuras; (warriorAuras, petAuras) = _getAurasData(packedWarriors); uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; totalDamage += getDamage(packedWarrior, warriorAuras, petAuras); penetration = getPenetration(packedWarrior, warriorAuras, petAuras); maxPenetration = maxPenetration > penetration ? maxPenetration : penetration; (hp, armor, dodge) = _getProtectionParams(packedWarrior, warriorAuras, petAuras); totalHp += hp; maxArmor = maxArmor > armor ? maxArmor : armor; maxDodge = maxDodge > dodge ? maxDodge : dodge; } } function _getAurasData(uint256[] memory packedWarriors) internal pure returns(uint256 warriorAuras, uint256 petAuras) { uint256 length = packedWarriors.length; warriorAuras = 0; petAuras = 0; uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; warriorAuras = enableAura(warriorAuras, (_unpackAuraValue(packedWarrior))); petAuras = enableAura(petAuras, (_getPetAura(_unpackPetData(_unpackPetValue(packedWarrior))))); } warriorAuras = filterWarriorAuras(warriorAuras, petAuras); return (warriorAuras, petAuras); } // Get bit value at position function isAuraSet(uint256 aura, uint256 auraIndex) internal pure returns (bool) { return aura & (uint256(0x01) << auraIndex) != 0; } // Set bit value at position function enableAura(uint256 a, uint256 n) internal pure returns (uint256) { return a | (uint256(0x01) << n); } //switch off warrior auras that are enabled in pets auras, pet aura have priority function filterWarriorAuras(uint256 _warriorAuras, uint256 _petAuras) internal pure returns(uint256) { return (_warriorAuras & _petAuras) ^ _warriorAuras; } function _getTournamentBattles(uint256 _numberOfContenders) internal pure returns(uint256) { return (_numberOfContenders * BATTLES_PER_CONTENDER / 2); } function getTournamentBattleResults(uint256[] memory combinedWarriors, uint256 _targetBlock) internal view returns (uint32[] memory results){ uint256 length = combinedWarriors.length; results = new uint32[](length); int256 damage1; int256 penetration1; uint256 hash; uint256 randomIndex; uint256 exp = 0; uint256 i; uint256 result; for(i = 0; i < length; i ++) { (damage1, penetration1) = _unpackAttackParams(combinedWarriors[i]); while(results[i] < BATTLES_PER_CONTENDER_SUM) { //if we just started generate new random source //or regenerate if we used all data from it if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock - i)), uint256(damage1) + now)); exp = 0; } //we do not fight with self if there are other warriors randomIndex = (_random(i + 1 < length ? i + 1 : i, length, hash, 1000 * 10**exp, 10**exp)); result = getTournamentBattleResult(damage1, penetration1, combinedWarriors[i], combinedWarriors[randomIndex], hash % (1000 * 10**exp) / 10**exp); results[result == 1 ? i : randomIndex] += 101;//icrement battle count 100 and +1 win results[result == 1 ? randomIndex : i] += 100;//increment only battle count 100 for loser if (results[randomIndex] >= BATTLES_PER_CONTENDER_SUM) { if (randomIndex < length - 1) { _swapValues(combinedWarriors, results, randomIndex, length - 1); } length --; } exp++; } } //filter battle count from results length = combinedWarriors.length; for(i = 0; i < length; i ++) { results[i] = results[i] % 100; } return results; } function _swapValues(uint256[] memory combinedWarriors, uint32[] memory results, uint256 id1, uint256 id2) internal pure { uint256 temp = combinedWarriors[id1]; combinedWarriors[id1] = combinedWarriors[id2]; combinedWarriors[id2] = temp; temp = results[id1]; results[id1] = results[id2]; results[id2] = uint32(temp); } function getTournamentBattleResult(int256 damage1, int256 penetration1, uint256 combinedWarrior1, uint256 combinedWarrior2, uint256 randomSource) internal pure returns (uint256) { int256 damage2; int256 penetration2; (damage2, penetration2) = _unpackAttackParams(combinedWarrior1); int256 totalHp1 = getCombinedTotalHP(combinedWarrior1, penetration2); int256 totalHp2 = getCombinedTotalHP(combinedWarrior2, penetration1); return _getBattleResult(damage1 * getBattleRandom(randomSource, 1) / 100, damage2 * getBattleRandom(randomSource, 10) / 100, totalHp1, totalHp2, randomSource); } /* COMMON BATTLE */ function _getBattleResult(int256 damage1, int256 damage2, int256 totalHp1, int256 totalHp2, uint256 randomSource) internal pure returns (uint256){ totalHp1 = (totalHp1 * (PRECISION * PRECISION) / damage2); totalHp2 = (totalHp2 * (PRECISION * PRECISION) / damage1); //if draw, let the coin decide who wins if (totalHp1 == totalHp2) return randomSource % 2 + 1; return totalHp1 > totalHp2 ? 1 : 2; } function getCombinedTotalHP(uint256 combinedData, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _unpackProtectionParams(combinedData); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function getTotalHP(uint256 packedData, uint256 warriorAuras, uint256 petAuras, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _getProtectionParams(packedData, warriorAuras, petAuras); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function _getTotalHp(int256 hp, int256 armor, int256 dodge, int256 enemyPenetration) internal pure returns(int256) { int256 piercingResult = (armor - enemyPenetration) < -(75 * PRECISION) ? -(75 * PRECISION) : (armor - enemyPenetration); int256 mitigation = (PRECISION - piercingResult * PRECISION / (PRECISION + piercingResult / 100) / 100); return (hp * PRECISION / mitigation + (hp * dodge / (100 * PRECISION))); } function _applyLevelBonus(int256 _value, uint256 _level) internal pure returns(int256) { _level -= 1; return int256(uint256(_value) * (LEVEL_BONUSES % (100 ** (_level + 1)) / (100 ** _level)) / 10); } function _getProtectionParams(uint256 packedData, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256 hp, int256 armor, int256 dodge) { uint256 rarityBonus = _unpackRarityBonusValue(packedData); uint256 petData = _unpackPetData(_unpackPetValue(packedData)); int256 strength = _unpackStrengthValue(packedData) * PRECISION + _getBattleBonus(BONUS_STR, rarityBonus, petData, warriorAuras, petAuras); int256 agility = _unpackAgilityValue(packedData) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); hp = 100 * PRECISION + strength + 7 * strength / 10 + _getBattleBonus(BONUS_HP, rarityBonus, petData, warriorAuras, petAuras);//add bonus hp hp = _applyLevelBonus(hp, _unpackLevelValue(packedData)); armor = (strength + 8 * strength / 10 + agility + _getBattleBonus(BONUS_ARMOR, rarityBonus, petData, warriorAuras, petAuras));//add bonus armor dodge = (2 * agility / 3); } function getDamage(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); int256 crit = (agility / 5 + intelligence / 4) + _getBattleBonus(BONUS_CRIT_CHANCE, rarityBonus, petData, warriorAuras, petAuras); int256 critMultiplier = (PRECISION + intelligence / 25) + _getBattleBonus(BONUS_CRIT_MULT, rarityBonus, petData, warriorAuras, petAuras); int256 damage = int256(_unpackBaseDamageValue(packedWarrior) * 3 * PRECISION / 2) + _getBattleBonus(BONUS_DAMAGE, rarityBonus, petData, warriorAuras, petAuras); return (_applyLevelBonus(damage, _unpackLevelValue(packedWarrior)) * (PRECISION + crit * critMultiplier / (100 * PRECISION))) / PRECISION; } function getPenetration(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); return (intelligence * 2 + agility + _getBattleBonus(BONUS_PENETRATION, rarityBonus, petData, warriorAuras, petAuras)); } /* BATTLE PVP */ //@param randomSource must be >= 1000 function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){ return int256(100 + _random(0, 11, randmSource, 100 * _step, _step)); } uint256 internal constant NO_AURA = 0; function getPVPBattleResult(uint256 packedData1, uint256 packedData2, uint256 randmSource) internal pure returns (uint256){ uint256 petAura1 = _computePVPPetAura(packedData1); uint256 petAura2 = _computePVPPetAura(packedData2); uint256 warriorAura1 = _computePVPWarriorAura(packedData1, petAura1); uint256 warriorAura2 = _computePVPWarriorAura(packedData2, petAura2); int256 damage1 = getDamage(packedData1, warriorAura1, petAura1) * getBattleRandom(randmSource, 1) / 100; int256 damage2 = getDamage(packedData2, warriorAura2, petAura2) * getBattleRandom(randmSource, 10) / 100; int256 totalHp1; int256 totalHp2; (totalHp1, totalHp2) = _computeContendersTotalHp(packedData1, warriorAura1, petAura1, packedData2, warriorAura1, petAura1); return _getBattleResult(damage1, damage2, totalHp1, totalHp2, randmSource); } function _computePVPPetAura(uint256 packedData) internal pure returns(uint256) { return enableAura(NO_AURA, _getPetAura(_unpackPetData(_unpackPetValue(packedData)))); } function _computePVPWarriorAura(uint256 packedData, uint256 petAuras) internal pure returns(uint256) { return filterWarriorAuras(enableAura(NO_AURA, _unpackAuraValue(packedData)), petAuras); } function _computeContendersTotalHp(uint256 packedData1, uint256 warriorAura1, uint256 petAura1, uint256 packedData2, uint256 warriorAura2, uint256 petAura2) internal pure returns(int256 totalHp1, int256 totalHp2) { int256 enemyPenetration = getPenetration(packedData2, warriorAura2, petAura2); totalHp1 = getTotalHP(packedData1, warriorAura1, petAura1, enemyPenetration); enemyPenetration = getPenetration(packedData1, warriorAura1, petAura1); totalHp2 = getTotalHP(packedData2, warriorAura1, petAura1, enemyPenetration); } function getRatingRange(uint256 _pvpCycle, uint256 _pvpInterval, uint256 _expandInterval) internal pure returns (uint256){ return 50 + (_pvpCycle * _pvpInterval / _expandInterval * 25); } function isMatching(int256 evenRating, int256 oddRating, int256 ratingGap) internal pure returns(bool) { return evenRating <= (oddRating + ratingGap) && evenRating >= (oddRating - ratingGap); } function sort(uint256[] memory data) internal pure { quickSort(data, int(0), int(data.length - 1)); } function quickSort(uint256[] memory arr, int256 left, int256 right) internal pure { int256 i = left; int256 j = right; if(i==j) return; uint256 pivot = arr[uint256(left + (right - left) / 2)]; while (i <= j) { while (arr[uint256(i)] < pivot) i++; while (pivot < arr[uint256(j)]) j--; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } function _swapPair(uint256[] memory matchingIds, uint256 id1, uint256 id2, uint256 id3, uint256 id4) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; temp = matchingIds[id3]; matchingIds[id3] = matchingIds[id4]; matchingIds[id4] = temp; } function _swapValues(uint256[] memory matchingIds, uint256 id1, uint256 id2) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; } function _getMatchingIds(uint256[] memory matchingIds, uint256 _pvpInterval, uint256 _skipCycles, uint256 _expandInterval) internal pure returns(uint256 matchingCount) { matchingCount = matchingIds.length; if (matchingCount == 0) return 0; uint256 warriorId; uint256 index; //sort matching ids quickSort(matchingIds, int256(0), int256(matchingCount - 1)); //find pairs int256 rating1; uint256 pairIndex = 0; int256 ratingRange; for(index = 0; index < matchingCount; index++) { //get packed value warriorId = matchingIds[index]; //unpack rating 1 rating1 = int256(_unpackRatingValue(warriorId)); ratingRange = int256(getRatingRange(_unpackCycleValue(warriorId) + _skipCycles, _pvpInterval, _expandInterval)); if (index > pairIndex && //check left neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index - 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index - 1, pairIndex + 1, index); //mark last pair position pairIndex += 2; } else if (index + 1 < matchingCount && //check right neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index + 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index, pairIndex + 1, index + 1); //mark last pair position pairIndex += 2; //skip next iteration index++; } } matchingCount = pairIndex; } function _getPVPBattleResults(uint256[] memory matchingIds, uint256 matchingCount, uint256 _targetBlock) internal view { uint256 exp = 0; uint256 hash = 0; uint256 result = 0; for (uint256 even = 0; even < matchingCount; even += 2) { if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock)), hash)); exp = 0; } //compute battle result 1 = even(left) id won, 2 - odd(right) id won result = getPVPBattleResult(matchingIds[even], matchingIds[even + 1], hash % (1000 * 10**exp) / 10**exp); require(result > 0 && result < 3); exp++; //if odd warrior won, swap his id with even warrior, //otherwise do nothing, //even ids are winning ids! odds suck! if (result == 2) { _swapValues(matchingIds, even, even + 1); } } } function _getLevel(uint256 _levelPoints) internal pure returns(uint256) { return _levelPoints / POINTS_TO_LEVEL; } } library DataTypes { // / @dev The main Warrior struct. Every warrior in CryptoWarriors is represented by a copy // / of this structure, so great care was taken to ensure that it fits neatly into // / exactly two 256-bit words. Note that the order of the members in this structure // / is important because of the byte-packing rules used by Ethereum. // / Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Warrior{ // The Warrior's identity code is packed into these 256-bits uint256 identity; uint64 cooldownEndBlock; /** every warriors starts from 1 lv (10 level points per level) */ uint64 level; /** PVP rating, every warrior starts with 100 rating */ int64 rating; // 0 - idle uint32 action; /** Set to the index in the levelRequirements array (see CryptoWarriorBase.levelRequirements) that represents * the current dungeon level requirement for warrior. This starts at zero. */ uint32 dungeonIndex; } } contract CryptoWarriorBase is PermissionControll, PVPListenerInterface { /*** EVENTS ***/ /// @dev The Arise event is fired whenever a new warrior comes into existence. This obviously /// includes any time a warrior is created through the ariseWarrior method, but it is also called /// when a new miner warrior is created. event Arise(address owner, uint256 warriorId, uint256 identity); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a warrior /// ownership is assigned, including dungeon rewards. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ uint256 public constant IDLE = 0; uint256 public constant PVE_BATTLE = 1; uint256 public constant PVP_BATTLE = 2; uint256 public constant TOURNAMENT_BATTLE = 3; //max pve dungeon level uint256 public constant MAX_LEVEL = 25; //how many points is needed to get 1 level uint256 public constant POINTS_TO_LEVEL = 10; /// @dev A lookup table contains PVE dungeon level requirements, each time warrior /// completes dungeon, next level requirement is set, until 25lv (250points) is reached. uint32[6] public dungeonRequirements = [ uint32(10), uint32(30), uint32(60), uint32(100), uint32(150), uint32(250) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Warrior struct for all Warriors in existence. The ID /// of each warrior is actually an index of this array. DataTypes.Warrior[] warriors; /// @dev A mapping from warrior IDs to the address that owns them. All warriors have /// some valid owner address, even miner warriors are created with a non-zero owner. mapping (uint256 => address) public warriorToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownersTokenCount; /// @dev A mapping from warrior IDs to an address that has been approved to call /// transferFrom(). Each Warrior can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public warriorToApproved; // 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; /// @dev The address of the ClockAuction contract that handles sales of warriors. This /// same contract handles both peer-to-peer sales as well as the miner sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev Assigns ownership of a specific warrior to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // When creating new warriors _from is 0x0, but we can't account that address. if (_from != address(0)) { _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); } _addTokenTo(_to, _tokenId); // Emit the transfer event. Transfer(_from, _to, _tokenId); } function _addTokenTo(address _to, uint256 _tokenId) internal { // Since the number of warriors is capped to '1 000 000' we can't overflow this ownersTokenCount[_to]++; // transfer ownership warriorToOwner[_tokenId] = _to; uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function _removeTokenFrom(address _from, uint256 _tokenId) internal { // ownersTokenCount[_from]--; warriorToOwner[_tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length - 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; } function _clearApproval(uint256 _tokenId) internal { if (warriorToApproved[_tokenId] != address(0)) { // clear any previously approved ownership exchange warriorToApproved[_tokenId] = address(0); } } function _createWarrior(uint256 _identity, address _owner, uint256 _cooldown, uint256 _level, uint256 _rating, uint256 _dungeonIndex) internal returns (uint256) { DataTypes.Warrior memory _warrior = DataTypes.Warrior({ identity : _identity, cooldownEndBlock : uint64(_cooldown), level : uint64(_level),//uint64(10), rating : int64(_rating),//int64(100), action : uint32(IDLE), dungeonIndex : uint32(_dungeonIndex)//uint32(0) }); uint256 newWarriorId = warriors.push(_warrior) - 1; // let's just be 100% sure we never let this happen. require(newWarriorId == uint256(uint32(newWarriorId))); // emit the arise event Arise(_owner, newWarriorId, _identity); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newWarriorId); return newWarriorId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; } } contract WarriorTokenImpl is CryptoWarriorBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoWarriors"; string public constant symbol = "CW"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant 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('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9f40b779)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /** @dev Checks if a given address is the current owner of the specified Warrior tokenId. * @param _claimant the address we are validating against. * @param _tokenId warrior id */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) && warriorToOwner[_tokenId] == _claimant; } function _ownerApproved(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) &&//0 address means token is burned warriorToOwner[_tokenId] == _claimant && warriorToApproved[_tokenId] == address(0); } /// @dev Checks if a given address currently has transferApproval for a particular Warrior. /// @param _claimant the address we are confirming warrior is approved for. /// @param _tokenId warrior id function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return warriorToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Warriors on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { warriorToApproved[_tokenId] = _approved; } /// @notice Returns the number of Warriors(tokens) owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownersTokenCount[_owner]; } /// @notice Transfers a Warrior to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoWarriors specifically) or your Warrior may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Warrior to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of warriors // through the allow + transferFrom flow. require(_to != address(saleAuction)); // You can only send your own warrior. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /// @notice Grant another address the right to transfer a specific Warrior via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Warrior that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Warrior owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Warrior to be transfered. /// @param _to The address that should take ownership of the Warrior. Can be any address, /// including the caller. /// @param _tokenId The ID of the Warrior to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Warriors currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return warriors.length; } /// @notice Returns the address currently assigned ownership of a given Warrior. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { require(_tokenId < warriors.length); owner = warriorToOwner[_tokenId]; } /// @notice Returns a list of all Warrior IDs assigned to an address. /// @param _owner The owner whose Warriors we are interested in. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { return ownedTokens[_owner]; } function tokensOfOwnerFromIndex(address _owner, uint256 _fromIndex, uint256 _count) external view returns(uint256[] memory ownerTokens) { require(_fromIndex < balanceOf(_owner)); uint256[] storage tokens = ownedTokens[_owner]; // uint256 ownerBalance = ownersTokenCount[_owner]; uint256 lenght = (ownerBalance - _fromIndex >= _count ? _count : ownerBalance - _fromIndex); // ownerTokens = new uint256[](lenght); for(uint256 i = 0; i < lenght; i ++) { ownerTokens[i] = tokens[_fromIndex + i]; } return ownerTokens; } /** * @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 { _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); Transfer(_owner, address(0), _tokenId); } } contract CryptoWarriorPVE is WarriorTokenImpl { uint256 internal constant MINER_PERK = 1; uint256 internal constant SUMMONING_SICKENESS = 12; uint256 internal constant PVE_COOLDOWN = 1 hours; uint256 internal constant PVE_DURATION = 15 minutes; /// @notice The payment required to use startPVEBattle(). uint256 public pveBattleFee = 10 finney; uint256 public constant PVE_COMPENSATION = 2 finney; /// @dev The address of the sibling contract that is used to implement warrior generation algorithm. SanctuaryInterface public sanctuary; /** @dev PVEStarted event. Emitted every time a warrior enters pve battle * @param owner Warrior owner * @param dungeonIndex Started dungeon index * @param warriorId Warrior ID that started PVE dungeon * @param battleEndBlock Block number, when started PVE dungeon will be completed */ event PVEStarted(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 battleEndBlock); /** @dev PVEFinished event. Emitted every time a warrior finishes pve battle * @param owner Warrior owner * @param dungeonIndex Finished dungeon index * @param warriorId Warrior ID that completed dungeon * @param cooldownEndBlock Block number, when cooldown on PVE battle entrance will be over * @param rewardId Warrior ID which was granted to the owner as battle reward */ event PVEFinished(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 cooldownEndBlock, uint256 rewardId); /// @dev Update the address of the sanctuary contract, can only be called by the Admin. /// @param _address An address of a sanctuary contract instance to be used from this point forward. function setSanctuaryAddress(address _address) external onlyAdmin { SanctuaryInterface candidateContract = SanctuaryInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSanctuary()); // Set the new contract address sanctuary = candidateContract; } function areUnique(uint256[] memory _warriorIds) internal pure returns(bool) { uint256 length = _warriorIds.length; uint256 j; for(uint256 i = 0; i < length; i++) { for(j = i + 1; j < length; j++) { if (_warriorIds[i] == _warriorIds[j]) return false; } } return true; } /// @dev Updates the minimum payment required for calling startPVE(). Can only /// be called by the COO address. function setPVEBattleFee(uint256 _pveBattleFee) external onlyAdmin { require(_pveBattleFee > PVE_COMPENSATION); pveBattleFee = _pveBattleFee; } /** @dev Returns PVE cooldown, after each battle, the warrior receives a * cooldown on the next entrance to the battle, cooldown depends on current warrior level, * which is multiplied by 1h. Special case: after receiving 25 lv, the cooldwon will be 14 days. * @param _levelPoints warrior level */ function getPVECooldown(uint256 _levelPoints) public pure returns (uint256) { uint256 level = CryptoUtils._getLevel(_levelPoints); if (level >= MAX_LEVEL) return (14 * 24 * PVE_COOLDOWN);//14 days return (PVE_COOLDOWN * level); } /** @dev Returns PVE duration, each battle have a duration, which depends on current warrior level, * which is multiplied by 15 min. At the end of the duration, warrior is becoming eligible to receive * battle reward (new warrior in shiny armor) * @param _levelPoints warrior level points */ function getPVEDuration(uint256 _levelPoints) public pure returns (uint256) { return CryptoUtils._getLevel(_levelPoints) * PVE_DURATION; } /// @dev Checks that a given warrior can participate in PVE battle. Requires that the /// current cooldown is finished and also checks that warrior is idle (does not participate in any action) /// and dungeon level requirement is satisfied function _isReadyToPVE(DataTypes.Warrior _warrior) internal view returns (bool) { return (_warrior.action == IDLE) && //is idle (_warrior.cooldownEndBlock <= uint64(block.number)) && //no cooldown (_warrior.level >= dungeonRequirements[_warrior.dungeonIndex]);//dungeon level requirement is satisfied } /// @dev Internal utility function to initiate pve battle, assumes that all battle /// requirements have been checked. function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number); // Emit the pve battle start event. PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock); } /// @dev Starts PVE battle for specified warrior, /// after battle, warrior owner will receive reward (Warrior) /// @param _warriorId A Warrior ready to PVE battle. function startPVE(uint256 _warriorId) external payable whenNotPaused { // Checks for payment. require(msg.value >= pveBattleFee); // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(_isReadyToPVE(warrior)); // All checks passed, let the battle begin! _triggerPVEStart(_warriorId); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - pveBattleFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail msg.sender.transfer(feeExcess); //send battle fee to beneficiary bankAddress.transfer(pveBattleFee - PVE_COMPENSATION); } function _ariseWarrior(address _owner, DataTypes.Warrior storage _warrior) internal returns(uint256) { uint256 identity = sanctuary.generateWarrior(_warrior.identity, CryptoUtils._getLevel(_warrior.level), _warrior.cooldownEndBlock - 1, 0); return _createWarrior(identity, _owner, block.number + (PVE_COOLDOWN * SUMMONING_SICKENESS / secondsPerBlock), 10, 100, 0); } /// @dev Internal utility function to finish pve battle, assumes that all battle /// finish requirements have been checked. function _triggerPVEFinish(uint256 _warriorId) internal { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to idle warrior.action = uint16(IDLE); // Compute an estimation of the cooldown time in blocks (based on current level). // and miner perc also reduces cooldown time by 4 times warrior.cooldownEndBlock = uint64((getPVECooldown(warrior.level) / CryptoUtils._getBonus(warrior.identity) / secondsPerBlock) + block.number); // cash completed dungeon index before increment uint256 dungeonIndex = warrior.dungeonIndex; // Increment the dungeon index, clamping it at 5, which is the length of the // dungeonRequirements array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. if (dungeonIndex < 5) { warrior.dungeonIndex += 1; } address owner = warriorToOwner[_warriorId]; // generate reward uint256 arisenWarriorId = _ariseWarrior(owner, warrior); //Emit event PVEFinished(owner, dungeonIndex, _warriorId, warrior.cooldownEndBlock, arisenWarriorId); } /** * @dev finishPVE can be called after battle time is over, * if checks are passed then battle result is computed, * and new warrior is awarded to owner of specified _warriord ID. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVE(uint256 _warriorId) external whenNotPaused { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that warrior participated in PVE battle action require(warrior.action == PVE_BATTLE); // And the battle time is over require(warrior.cooldownEndBlock <= uint64(block.number)); // When the all checks done, calculate actual battle result _triggerPVEFinish(_warriorId); //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION); } /** * @dev finishPVEBatch same as finishPVE but for multiple warrior ids. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVEBatch(uint256[] _warriorIds) external whenNotPaused { uint256 length = _warriorIds.length; //check max number of bach finish pve require(length <= 20); uint256 blockNumber = block.number; uint256 index; //all warrior ids must be unique require(areUnique(_warriorIds)); //check prerequisites for(index = 0; index < length; index ++) { DataTypes.Warrior storage warrior = warriors[_warriorIds[index]]; require( // Check that the warrior exists. warrior.identity != 0 && // Check that warrior participated in PVE battle action warrior.action == PVE_BATTLE && // And the battle time is over warrior.cooldownEndBlock <= blockNumber ); } // When the all checks done, calculate actual battle result for(index = 0; index < length; index ++) { _triggerPVEFinish(_warriorIds[index]); } //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION * length); } } contract CryptoWarriorSanctuary is CryptoWarriorPVE { uint256 internal constant RARE = 3; function burnWarrior(uint256 _warriorId, address _owner) whenNotPaused external { require(msg.sender == address(sanctuary)); // Caller must own the warrior. require(_ownerApproved(_owner, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE);//is idle // Rarity of burned warrior must be less or equal RARE (3) require(CryptoUtils.getRarityValue(warrior.identity) <= RARE); // Warriors with MINER perc are not allowed to be berned require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK); _burn(_owner, _warriorId); } function ariseWarrior(uint256 _identity, address _owner, uint256 _cooldown) whenNotPaused external returns(uint256){ require(msg.sender == address(sanctuary)); return _createWarrior(_identity, _owner, _cooldown, 10, 100, 0); } } contract CryptoWarriorPVP is CryptoWarriorSanctuary { PVPInterface public battleProvider; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setBattleProviderAddress(address _address) external onlyAdmin { PVPInterface candidateContract = PVPInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPProvider()); // Set the new contract address battleProvider = candidateContract; } function _packPVPData(uint256 _warriorId, DataTypes.Warrior storage warrior) internal view returns(uint256){ return CryptoUtils._packWarriorPvpData(warrior.identity, uint256(warrior.rating), 0, _warriorId, warrior.level); } function _triggerPVPSignUp(uint256 _warriorId, uint256 fee) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; uint256 packedWarrior = _packPVPData(_warriorId, warrior); // addPVPContender will throw if fee fails. battleProvider.addPVPContender.value(fee)(msg.sender, packedWarrior); warrior.action = uint16(PVP_BATTLE); } /* * @title signUpForPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function signUpForPVP(uint256 _warriorId) public payable whenNotPaused {//done // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // sanity check require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE); // Define the current price of the auction. uint256 fee = battleProvider.getPVPEntranceFee(warrior.level); // Checks for payment. require(msg.value >= fee); // All checks passed, put the warrior to the queue! _triggerPVPSignUp(_warriorId, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of warrior.action == IDLE check // will fail msg.sender.transfer(feeExcess); } function _grandPVPWinnerReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 1 level, add 10 level points uint256 level = warrior.level; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level = level + POINTS_TO_LEVEL; warrior.level = uint64(level > (MAX_LEVEL * POINTS_TO_LEVEL) ? (MAX_LEVEL * POINTS_TO_LEVEL) : level); } // give 100 rating for levelUp and 30 for win warrior.rating += 130; // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPLoserReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 0.5 level uint256 oldLevel = warrior.level; uint256 level = oldLevel; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level += (POINTS_TO_LEVEL / 2); warrior.level = uint64(level); } // give 100 rating for levelUp if happens and -30 for lose int256 newRating = warrior.rating + (CryptoUtils._getLevel(level) > CryptoUtils._getLevel(oldLevel) ? int256(100 - 30) : int256(-30)); // rating can't be less than 0 and more than 1000000000 warrior.rating = int64((newRating >= 0) ? (newRating > 1000000000 ? 1000000000 : newRating) : 0); // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPRewards(uint256[] memory warriorsData, uint256 matchingCount) internal { for(uint256 id = 0; id < matchingCount; id += 2){ // // winner, even ids are winners! _grandPVPWinnerReward(CryptoUtils._unpackIdValue(warriorsData[id])); // // loser, they are odd... _grandPVPLoserReward(CryptoUtils._unpackIdValue(warriorsData[id + 1])); } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function pvpFinished(uint256[] warriorsData, uint256 matchingCount) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); _grandPVPRewards(warriorsData, matchingCount); } function pvpContenderRemoved(uint256 _warriorId) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grab warrior storage reference DataTypes.Warrior storage warrior = warriors[_warriorId]; //specified warrior must be in pvp state require(warrior.action == PVP_BATTLE); //all checks done //set warrior state to IDLE warrior.action = uint16(IDLE); } } contract CryptoWarriorTournament is CryptoWarriorPVP { uint256 internal constant GROUP_SIZE = 5; function _ownsAll(address _claimant, uint256[] memory _warriorIds) internal view returns (bool) { uint256 length = _warriorIds.length; for(uint256 i = 0; i < length; i++) { if (!_ownerApproved(_claimant, _warriorIds[i])) return false; } return true; } function _isReadyToTournament(DataTypes.Warrior storage _warrior) internal view returns(bool){ return _warrior.level >= 50 && _warrior.action == IDLE;//must not participate in any action } function _packTournamentData(uint256[] memory _warriorIds) internal view returns(uint256[] memory tournamentData) { tournamentData = new uint256[](GROUP_SIZE); uint256 warriorId; for(uint256 i = 0; i < GROUP_SIZE; i++) { warriorId = _warriorIds[i]; tournamentData[i] = _packPVPData(warriorId, warriors[warriorId]); } return tournamentData; } // @dev Internal utility function to sign up to tournament, // assumes that all battle requirements have been checked. function _triggerTournamentSignUp(uint256[] memory _warriorIds, uint256 fee) internal { //pack warrior ids into into uint256 uint256[] memory tournamentData = _packTournamentData(_warriorIds); for(uint256 i = 0; i < GROUP_SIZE; i++) { // Set warrior current action to tournament battle warriors[_warriorIds[i]].action = uint16(TOURNAMENT_BATTLE); } battleProvider.addTournamentContender.value(fee)(msg.sender, tournamentData); } function signUpForTournament(uint256[] _warriorIds) public payable { // //check that there is enough funds to pay entrance fee uint256 fee = battleProvider.getTournamentThresholdFee(); require(msg.value >= fee); // //check that warriors group is exactly of allowed size require(_warriorIds.length == GROUP_SIZE); // //message sender must own all the specified warrior IDs require(_ownsAll(msg.sender, _warriorIds)); // //check all warriors are unique require(areUnique(_warriorIds)); // //check that all warriors are 25 lv and IDLE for(uint256 i = 0; i < GROUP_SIZE; i ++) { // Grab a reference to the warrior in storage. require(_isReadyToTournament(warriors[_warriorIds[i]])); } //all checks passed, trigger sign up _triggerTournamentSignUp(_warriorIds, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the fee so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToTournament check // will fail msg.sender.transfer(feeExcess); } function _setIDLE(uint256 warriorIds) internal { for(uint256 i = 0; i < GROUP_SIZE; i ++) { warriors[CryptoUtils._unpackWarriorId(warriorIds, i)].action = uint16(IDLE); } } function _freeWarriors(uint256[] memory packedContenders) internal { uint256 length = packedContenders.length; for(uint256 i = 0; i < length; i ++) { //set participants action to IDLE _setIDLE(packedContenders[i]); } } function tournamentFinished(uint256[] packedContenders) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grad rewards and set IDLE action _freeWarriors(packedContenders); } } contract CryptoWarriorAuction is CryptoWarriorTournament { // @notice The auction contract variables are defined in CryptoWarriorBase to allow // us to refer to them in WarriorTokenImpl to prevent accidental transfers. // `saleAuction` refers to the auction for miner and p2p sale of warriors. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyAdmin { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a warrior up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _warriorId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If warrior is already on any auction, this will throw // because it will be owned by the auction contract. require(_ownerApproved(msg.sender, _warriorId)); // Ensure the warrior is not busy to prevent the auction // contract creation while warrior is in any kind of battle (PVE, PVP, TOURNAMENT). require(warriors[_warriorId].action == IDLE); _approve(_warriorId, address(saleAuction)); // Sale auction throws if inputs are invalid and clears // transfer approval after escrowing the warrior. saleAuction.createAuction( _warriorId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract CryptoWarriorIssuer is CryptoWarriorAuction { // Limits the number of warriors the contract owner can ever create uint256 public constant MINER_CREATION_LIMIT = 2880;//issue every 15min for one month // Constants for miner auctions. uint256 public constant MINER_STARTING_PRICE = 100 finney; uint256 public constant MINER_END_PRICE = 50 finney; uint256 public constant MINER_AUCTION_DURATION = 1 days; uint256 public minerCreatedCount; /// @dev Generates a new miner warrior with MINER perk of COMMON rarity /// creates an auction for it. function createMinerAuction() external onlyIssuer { require(minerCreatedCount < MINER_CREATION_LIMIT); minerCreatedCount++; uint256 identity = sanctuary.generateWarrior(minerCreatedCount, 0, block.number - 1, MINER_PERK); uint256 warriorId = _createWarrior(identity, bankAddress, 0, 10, 100, 0); _approve(warriorId, address(saleAuction)); saleAuction.createAuction( warriorId, _computeNextMinerPrice(), MINER_END_PRICE, MINER_AUCTION_DURATION, bankAddress ); } /// @dev Computes the next miner auction starting price, given /// the average of the past 5 prices * 2. function _computeNextMinerPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageMinerSalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice * 3 / 2;//confirmed // We never auction for less than starting price if (nextPrice < MINER_STARTING_PRICE) { nextPrice = MINER_STARTING_PRICE; } return nextPrice; } } contract CoreRecovery is CryptoWarriorIssuer { bool public allowRecovery = true; //data model //0 - identity //1 - cooldownEndBlock //2 - level //3 - rating //4 - index function recoverWarriors(uint256[] recoveryData, address[] owners) external onlyAdmin whenPaused { //check that recory action is allowed require(allowRecovery); uint256 length = owners.length; //check that number of owners corresponds to recover data length require(length == recoveryData.length / 5); for(uint256 i = 0; i < length; i++) { _createWarrior(recoveryData[i * 5], owners[i], recoveryData[i * 5 + 1], recoveryData[i * 5 + 2], recoveryData[i * 5 + 3], recoveryData[i * 5 + 4]); } } //recovery is a one time action, once it is done no more recovery actions allowed function recoveryDone() external onlyAdmin { allowRecovery = false; } } contract CryptoWarriorCore is CoreRecovery { /// @notice Creates the main CryptoWarrior smart contract instance. function CryptoWarriorCore() public { // Starts paused. paused = true; // the creator of the contract is the initial Admin adminAddress = msg.sender; // the creator of the contract is also the initial COO issuerAddress = msg.sender; // the creator of the contract is also the initial Bank bankAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here /// (Hopefully, we can prevent user accidents.) function() external payable { require(false); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyAdmin whenPaused { require(address(saleAuction) != address(0)); require(address(sanctuary) != address(0)); require(address(battleProvider) != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function getBeneficiary() external view returns(address) { return bankAddress; } function isPVPListener() public pure returns (bool) { return true; } /** *@param _warriorIds array of warriorIds, * for those IDs warrior data will be packed into warriorsData array *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriors(uint256[] _warriorIds) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; warriorsData = new uint256[](_warriorIds.length * stepSize); for(uint256 i = 0; i < _warriorIds.length; i++) { _setWarriorData(warriorsData, warriors[_warriorIds[i]], i * stepSize); } } /** *@param indexFrom index in global warrior storage (aka warriorId), * from this index(including), warriors data will be gathered *@param count Number of warriors to include in packed data *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; //check length uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom); warriorsData = new uint256[](lenght * stepSize); for(uint256 i = 0; i < lenght; i ++) { _setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize); } } function getWarriorOwners(uint256[] _warriorIds) external view returns (address[] memory owners) { uint256 lenght = _warriorIds.length; owners = new address[](lenght); for(uint256 i = 0; i < lenght; i ++) { owners[i] = warriorToOwner[_warriorIds[i]]; } } function _setWarriorData(uint256[] memory warriorsData, DataTypes.Warrior storage warrior, uint256 id) internal view { warriorsData[id] = uint256(warrior.identity);//0 warriorsData[id + 1] = uint256(warrior.cooldownEndBlock);//1 warriorsData[id + 2] = uint256(warrior.level);//2 warriorsData[id + 3] = uint256(warrior.rating);//3 warriorsData[id + 4] = uint256(warrior.action);//4 warriorsData[id + 5] = uint256(warrior.dungeonIndex);//5 } function getWarrior(uint256 _id) external view returns ( uint256 identity, uint256 cooldownEndBlock, uint256 level, uint256 rating, uint256 action, uint256 dungeonIndex ) { DataTypes.Warrior storage warrior = warriors[_id]; identity = uint256(warrior.identity); cooldownEndBlock = uint256(warrior.cooldownEndBlock); level = uint256(warrior.level); rating = uint256(warrior.rating); action = uint256(warrior.action); dungeonIndex = uint256(warrior.dungeonIndex); } } /* @title Handles creating pvp battles every 15 min.*/ contract PVP is PausableBattle, PVPInterface { /* PVP BATLE */ /** list of packed warrior data that will participate in next PVP session. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving queue modification. */ uint256[100] public pvpQueue; // //queue size uint256 public pvpQueueSize = 0; // @dev A mapping from owner address to booty in WEI // booty is acquired in PVP and Tournament battles and can be // withdrawn with grabBooty method by the owner of the loot mapping (address => uint256) public ownerToBooty; // @dev A mapping from warrior id to owners address mapping (uint256 => address) internal warriorToOwner; // An approximation of currently how many seconds are in between blocks. uint256 internal secondsPerBlock = 15; // Cut owner takes from, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public pvpOwnerCut; // Values 0-10,000 map to 0%-100% //this % of the total bets will be sent as //a reward to address, that triggered finishPVP method uint256 public pvpMaxIncentiveCut; /// @notice The payment base required to use startPVP(). // pvpBattleFee * (warrior.level / POINTS_TO_LEVEL) uint256 internal pvpBattleFee = 10 finney; uint256 public constant PVP_INTERVAL = 15 minutes; uint256 public nextPVPBatleBlock = 0; //number of WEI in hands of warrior owners uint256 public totalBooty = 0; /* TOURNAMENT */ uint256 public constant FUND_GATHERING_TIME = 24 hours; uint256 public constant ADMISSION_TIME = 12 hours; uint256 public constant RATING_EXPAND_INTERVAL = 1 hours; uint256 internal constant SAFETY_GAP = 5; uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney; //tournamentContenders size uint256 public tournamentQueueSize = 0; // Values 0-10,000 map to 0%-100% uint256 public tournamentBankCut; /** tournamentEndBlock, tournament is eligible to be finished only * after block.number >= tournamentEndBlock * it depends on FUND_GATHERING_TIME and ADMISSION_TIME */ uint256 public tournamentEndBlock; //number of WEI in tournament bank uint256 public currentTournamentBank = 0; uint256 public nextTournamentBank = 0; PVPListenerInterface internal pvpListener; /* EVENTS */ /** @dev TournamentScheduled event. Emitted every time a tournament is scheduled * @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament * is eligible to be finished or rescheduled */ event TournamentScheduled(uint256 tournamentEndBlock); /** @dev PVPScheduled event. Emitted every time a tournament is scheduled * @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle * is eligible to be finished or rescheduled */ event PVPScheduled(uint256 nextPVPBatleBlock); /** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle * @param owner Warrior owner * @param warriorId Warrior ID that entered PVP queue * @param entranceFee fee in WEI warrior owner payed to enter PVP */ event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee); /** @dev PVPFinished event. Emitted every time a pvp battle is finished * @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers * @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers * @param matchingCount total number of warriors that fought in current pvp session and got rewards, * if matchingCount < participants.length then all IDs that are >= matchingCount will * remain in waiting room, until they are matched. */ event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount); /** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient * in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually * @param recipient address for whom send failed * @param amount number of WEI we failed to send */ event BootySendFailed(address recipient, uint256 amount); /** @dev BootyGrabbed event * @param receiver address who grabbed his booty * @param amount number of WEI */ event BootyGrabbed(address receiver, uint256 amount); /** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner. * @param warriorId id of the removed warrior */ event PVPContenderRemoved(uint256 warriorId, address owner); function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public { require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000); pvpOwnerCut = _pvpCut; tournamentBankCut = _tournamentBankCut; pvpMaxIncentiveCut = _pvpMaxIncentiveCut; } /** @dev grabBooty sends to message sender his booty in WEI */ function grabBooty() external { uint256 booty = ownerToBooty[msg.sender]; require(booty > 0); require(totalBooty >= booty); ownerToBooty[msg.sender] = 0; totalBooty -= booty; msg.sender.transfer(booty); //emit event BootyGrabbed(msg.sender, booty); } function safeSend(address _recipient, uint256 _amaunt) internal { uint256 failedBooty = sendBooty(_recipient, _amaunt); if (failedBooty > 0) { totalBooty += failedBooty; } } function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) { bool success = _recipient.send(_amaunt); if (!success && _amaunt > 0) { ownerToBooty[_recipient] += _amaunt; BootySendFailed(_recipient, _amaunt); return _amaunt; } return 0; } //@returns block number, after this block tournament is opened for admission function getTournamentAdmissionBlock() public view returns(uint256) { uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock); return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval; } //schedules next turnament time(block) function _scheduleTournament() internal { //we can chedule only if there is nobody in tournament queue and //time of tournament battle have passed if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) { tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number; TournamentScheduled(tournamentEndBlock); } } /// @dev Updates the minimum payment required for calling startPVP(). Can only /// be called by the COO address, and only if pvp queue is empty. function setPVPEntranceFee(uint256 value) external onlyOwner { require(pvpQueueSize == 0); pvpBattleFee = value; } //@returns PVP entrance fee for specified warrior level //@param _levelPoints NB! function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) { return pvpBattleFee * CryptoUtils._getLevel(_levelPoints); } //level can only be > 0 and <= 25 function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) { return pvpBattleFee * _level; } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalBet max value is 1000 finney, and _contendersCut aka // (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalBet. return _totalBet * _contendersCut / 10000; } function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require() // statement in the BattleProvider constructor). // _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut); } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * _incentiveCut / 10000; } ///@dev computes incentive cut for specified loot, /// Values 0-10,000 map to 0%-100% /// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD, /// then cut is lowered to be equal to MAX_INCENTIVE_REWARD. /// minimum cut is 0.01% /// this % of the total bets will be sent as /// a reward to address, that triggered finishPVP method function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) { uint256 result = _totalSessionLoot * maxIncentiveCut / 10000; result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot; //min cut is 0.01% return result > 0 ? result : 1; } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * pvpOwnerCut / 10000; } // @dev Computes tournament bank cut // @param _totalSessionLoot - total session loot. function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * tournamentBankCut / 10000; } function indexOf(uint256 _warriorId) internal view returns(int256) { uint256 length = uint256(pvpQueueSize); for(uint256 i = 0; i < length; i ++) { if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i); } return -1; } function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) { uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount); return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut)); } function maxPVPContenders() external view returns(uint256){ return pvpQueue.length; } function getPVPState() external view returns (uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward) { uint256[] memory pvpData = _packPVPData(); contendersCount = pvpQueueSize; matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL); endBlock = nextPVPBatleBlock; incentiveReward = getPVPIncentiveReward(pvpData, matchingCount); } function canFinishPVP() external view returns(bool) { return nextPVPBatleBlock <= block.number && CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1; } function _clarifyPVPSchedule() internal { uint256 length = pvpQueueSize; uint256 currentBlock = block.number; uint256 nextBattleBlock = nextPVPBatleBlock; //if battle not scheduled, schedule battle if (nextBattleBlock <= currentBlock) { //if queue not empty update cycles if (length > 0) { uint256 packedWarrior; uint256 cycleSkip = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = pvpQueue[i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip); } } nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); //if pvp queue will be full and there is still too much time left, then let the battle begin! } else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) { nextBattleBlock = currentBlock + SAFETY_GAP; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); } } /// @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal { _clarifyPVPSchedule(); //number of pvp cycles the warrior is waiting for suitable enemy match //increment every time when finishPVP is called and no suitable enemy match was found _packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0); //record contender data pvpQueue[pvpQueueSize++] = _packedWarrior; warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner; //Emit event PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee); } function _noMatchingPairs() internal view returns(bool) { uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); return matchingCount == 0; } /* * @title startPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused { // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); //contender can be added only while PVP is scheduled in future //or no matching warrior pairs found require(nextPVPBatleBlock > block.number || _noMatchingPairs()); // Check that the warrior exists. require(_packedWarrior != 0); //owner must withdraw all loot before contending pvp require(ownerToBooty[_owner] == 0); //check that there is enough room for new participants require(pvpQueueSize < pvpQueue.length); // Checks for payment. uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior)); require(msg.value >= fee); // // All checks passed, put the warrior to the queue! _triggerNewPVPContender(_owner, _packedWarrior, fee); } function _packPVPData() internal view returns(uint256[] memory matchingIds) { uint256 length = pvpQueueSize; matchingIds = new uint256[](length); for(uint256 i = 0; i < length; i++) { matchingIds[i] = pvpQueue[i]; } return matchingIds; } function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) { //compute session booty uint256 sessionLoot = 0; for(uint256 i = 0; i < matchingCount; i++) { sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i])); } return sessionLoot; } function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount) internal returns(uint256) { uint256 booty = 0; uint256 packedWarrior; uint256 failedBooty = 0; uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount); uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut); uint256 contendersCut = _getPVPContendersCut(incentiveCut); for(uint256 id = 0; id < matchingCount; id++) { //give reward to warriors that fought hard //winner, even ids are winners! packedWarrior = _packedWarriors[id]; // //give winner deserved booty 80% from both bets //must be computed before level reward! booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) + _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1])); // //send reward to warrior owner failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut)); //loser, they are odd... //skip them, as they deserve none! id ++; } failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty)); if (failedBooty > 0) { totalBooty += failedBooty; } //if tournament admission start time not passed //add tournament cut to current tournament bank, //otherwise to next tournament bank if (getTournamentAdmissionBlock() > block.number) { currentTournamentBank += _computeTournamentCut(sessionBooty); } else { nextTournamentBank += _computeTournamentCut(sessionBooty); } //compute incentive reward return _computeIncentiveReward(sessionBooty, incentiveCut); } function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal { uint32 length = uint32(matchingIds.length - matchingCount); uint256 packedWarrior; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = matchingIds[matchingCount + i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles); } //trim queue pvpQueueSize = length; } function _computeCycleSkip() internal view returns(uint256) { uint256 number = block.number; return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1; } function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){ uint256 length = pvpData.length; owners = new address[](length); for(uint256 i = 0; i < length; i ++) { owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])]; } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){ // //compute battle results CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock); // //mark not fought warriors and trim queue _increaseCycleAndTrimQueue(pvpData, matchingCount); // //schedule next battle time nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number; // //schedule tournament //if contendersCount is 0 and tournament not scheduled, schedule tournament //NB MUST be before _grandPVPRewards() _scheduleTournament(); // compute and grand rewards to warriors, // put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number); // and require(number of pairs > 1); uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount); // //notify pvp listener contract pvpListener.pvpFinished(pvpData, matchingCount); // //fire event PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount); PVPScheduled(nextPVPBatleBlock); return incentiveReward; } /** * @dev finishPVP this method finds matches of warrior pairs * in waiting room and computes result of their fights. * * The winner gets +1 level, the loser gets +0.5 level * The winning player gets +130 rating * The losing player gets -30 or 70 rating (if warrior levelUps after battle) . * can be called once in 15min. * NB If the warrior is not picked up in an hour, then we expand the range * of selection by 25 rating each hour. */ function finishPVP() public PVPNotPaused { // battle interval is over require(nextPVPBatleBlock <= block.number); // //match warriors uint256[] memory pvpData = _packPVPData(); //match ids and sort them according to matching uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); // we have at least 1 matching battle pair require(matchingCount > 1); // When the all checks done, calculate actual battle result uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Removes specified warrior from PVP queue // sets warrior free (IDLE) and returns pvp entrance fee to owner // @notice This is a state-modifying function that can // be called while the contract is paused. // @param _warriorId - ID of warrior in PVP queue function removePVPContender(uint256 _warriorId) external{ uint256 queueSize = pvpQueueSize; require(queueSize > 0); // Caller must be owner of the specified warrior require(warriorToOwner[_warriorId] == msg.sender); //warrior must be in pvp queue int256 warriorIndex = indexOf(_warriorId); require(warriorIndex >= 0); //grab warrior data uint256 warriorData = pvpQueue[uint32(warriorIndex)]; //warrior cycle must be >= 4 (> than 1 hour) require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4); //remove from queue if (uint256(warriorIndex) < queueSize - 1) { pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1]; } pvpQueueSize --; //notify battle listener pvpListener.pvpContenderRemoved(_warriorId); //return pvp bet msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); //Emit event PVPContenderRemoved(_warriorId, msg.sender); } function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){ uint256 length = warriorIds.length; uint32[] memory cycles = new uint32[](length); int256 index; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i ++) { index = indexOf(warriorIds[i]); cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0; } return cycles; } // @dev Remove all PVP contenders from PVP queue // and return all bets to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllPVPContenders() external onlyOwner PVPPaused { //remove all pvp contenders uint256 length = pvpQueueSize; uint256 warriorData; uint256 warriorId; uint256 failedBooty; address owner; pvpQueueSize = 0; for(uint256 i = 0; i < length; i++) { //grab warrior data warriorData = pvpQueue[i]; warriorId = CryptoUtils._unpackIdValue(warriorData); //notify battle listener pvpListener.pvpContenderRemoved(uint32(warriorId)); owner = warriorToOwner[warriorId]; //return pvp bet failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); } totalBooty += failedBooty; } } contract Tournament is PVP { uint256 internal constant GROUP_SIZE = 5; uint256 internal constant DATA_SIZE = 2; uint256 internal constant THRESHOLD = 300; /** list of warrior IDs that will participate in next tournament. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving array modification. */ uint256[160] public tournamentQueue; /**The cost of participation in the tournament is 1% of its current prize fund, * money is added to the prize fund. measured in basis points (1/100 of a percent). * Values 0-10,000 map to 0%-100% */ uint256 internal tournamentEntranceFeeCut = 100; // Values 0-10,000 map to 0%-100% => 20% uint256 public tournamentOwnersCut; uint256 public tournamentIncentiveCut; /** @dev TournamentNewContender event. Emitted every time a warrior enters tournament * @param owner Warrior owner * @param warriorIds 5 Warrior IDs that entered tournament, packed into one uint256 * see CryptoUtils._packWarriorIds */ event TournamentNewContender(address owner, uint256 warriorIds, uint256 entranceFee); /** @dev TournamentFinished event. Emitted every time a tournament is finished * @param owners array of warrior group owners packed to uint256 * @param results number of wins for each group * @param tournamentBank current tournament bank * see CryptoUtils._packWarriorIds */ event TournamentFinished(uint256[] owners, uint32[] results, uint256 tournamentBank); function Tournament(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public PVP(_pvpCut, _tournamentBankCut, _pvpMaxIncentiveCut) { require((_tournamentOwnersCut + _tournamentIncentiveCut) <= 10000); tournamentOwnersCut = _tournamentOwnersCut; tournamentIncentiveCut = _tournamentIncentiveCut; } // @dev Computes incentive reward for launching tournament finishTournament() // @param _tournamentBank function _computeTournamentIncentiveReward(uint256 _currentBank, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * _incentiveCut / 10000; } function _computeTournamentContenderCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. return 10000 - tournamentOwnersCut - _incentiveCut; } function _computeTournamentBeneficiaryFee(uint256 _currentBank) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * tournamentOwnersCut / 10000; } // @dev set tournament entrance fee cut, can be set only if // tournament queue is empty // @param _cut range from 0 - 10000, mapped to 0-100% function setTournamentEntranceFeeCut(uint256 _cut) external onlyOwner { //cut must be less or equal 100& require(_cut <= 10000); //tournament queue must be empty require(tournamentQueueSize == 0); //checks passed, set cut tournamentEntranceFeeCut = _cut; } function getTournamentEntranceFee() external view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut / 10000; } //@dev returns tournament entrance fee - 3% threshold function getTournamentThresholdFee() public view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 / 10000; } //@dev returns max allowed tournament contenders, public because of internal use function maxTournamentContenders() public view returns(uint256){ return tournamentQueue.length / DATA_SIZE; } function canFinishTournament() external view returns(bool) { return tournamentEndBlock <= block.number && tournamentQueueSize > 0; } // @dev Internal utility function to sigin up to tournament, // assumes that all battle requirements have been checked. function _triggerNewTournamentContender(address _owner, uint256[] memory _tournamentData, uint256 _fee) internal { //pack warrior ids into uint256 currentTournamentBank += _fee; uint256 packedWarriorIds = CryptoUtils._packWarriorIds(_tournamentData); //make composite warrior out of 5 warriors uint256 combinedWarrior = CryptoUtils._combineWarriors(_tournamentData); //add to queue //icrement tournament queue uint256 size = tournamentQueueSize++ * DATA_SIZE; //record tournament data tournamentQueue[size++] = packedWarriorIds; tournamentQueue[size++] = combinedWarrior; warriorToOwner[CryptoUtils._unpackWarriorId(packedWarriorIds, 0)] = _owner; // //Emit event TournamentNewContender(_owner, packedWarriorIds, _fee); } function addTournamentContender(address _owner, uint256[] _tournamentData) external payable TournamentNotPaused{ // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); // //check current tournament bank > 0 require(pvpBattleFee == 0 || currentTournamentBank > 0); // //check that there is enough funds to pay entrance fee uint256 fee = getTournamentThresholdFee(); require(msg.value >= fee); //owner must withdraw all booty before contending pvp require(ownerToBooty[_owner] == 0); // //check that warriors group is exactly of allowed size require(_tournamentData.length == GROUP_SIZE); // //check that there is enough room for new participants require(tournamentQueueSize < maxTournamentContenders()); // //check that admission started require(block.number >= getTournamentAdmissionBlock()); //check that admission not ended require(block.number <= tournamentEndBlock); //all checks passed, trigger sign up _triggerNewTournamentContender(_owner, _tournamentData, fee); } //@dev collect all combined warriors data function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) { uint256 length = tournamentQueueSize; warriorsData = new uint256[](length); for(uint256 i = 0; i < length; i ++) { // Grab the combined warrior data in storage. warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1]; } return warriorsData; } function getTournamentState() external view returns (uint256 contendersCount, uint256 bank, uint256 admissionStartBlock, uint256 endBlock, uint256 incentiveReward) { contendersCount = tournamentQueueSize; bank = currentTournamentBank; admissionStartBlock = getTournamentAdmissionBlock(); endBlock = tournamentEndBlock; incentiveReward = _computeTournamentIncentiveReward(bank, _computeIncentiveCut(bank, tournamentIncentiveCut)); } function _repackToCombinedIds(uint256[] memory _warriorsData) internal view { uint256 length = _warriorsData.length; for(uint256 i = 0; i < length; i ++) { _warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computeTournamentBooty(uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // _totalBattles is guaranteed to be > 0 and <= 400, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. // return _currentBank * (10000 - tournamentOwnersCut - _incentiveCut) * _result / 10000 / _totalBattles; return _currentBank * _contenderResult / _totalBattles; } function _grandTournamentBooty(uint256 _warriorIds, uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal returns (uint256) { uint256 warriorId = CryptoUtils._unpackWarriorId(_warriorIds, 0); address owner = warriorToOwner[warriorId]; uint256 booty = _computeTournamentBooty(_currentBank, _contenderResult, _totalBattles); return sendBooty(owner, booty); } function _grandTournamentRewards(uint256 _currentBank, uint256[] memory _warriorsData, uint32[] memory _results) internal returns (uint256){ uint256 length = _warriorsData.length; uint256 totalBattles = CryptoUtils._getTournamentBattles(length) * 10000;//*10000 required for booty computation uint256 incentiveCut = _computeIncentiveCut(_currentBank, tournamentIncentiveCut); uint256 contenderCut = _computeTournamentContenderCut(incentiveCut); uint256 failedBooty = 0; for(uint256 i = 0; i < length; i ++) { //grand rewards failedBooty += _grandTournamentBooty(_warriorsData[i], _currentBank, _results[i] * contenderCut, totalBattles); } //send beneficiary fee failedBooty += sendBooty(pvpListener.getBeneficiary(), _computeTournamentBeneficiaryFee(_currentBank)); if (failedBooty > 0) { totalBooty += failedBooty; } return _computeTournamentIncentiveReward(_currentBank, incentiveCut); } function _repackToWarriorOwners(uint256[] memory warriorsData) internal view { uint256 length = warriorsData.length; for (uint256 i = 0; i < length; i ++) { warriorsData[i] = uint256(warriorToOwner[CryptoUtils._unpackWarriorId(warriorsData[i], 0)]); } } function _triggerFinishTournament() internal returns(uint256){ //hold 10 random battles for each composite warrior uint256[] memory warriorsData = getCombinedWarriors(); uint32[] memory results = CryptoUtils.getTournamentBattleResults(warriorsData, tournamentEndBlock - 1); //repack combined warriors id _repackToCombinedIds(warriorsData); //notify pvp listener pvpListener.tournamentFinished(warriorsData); //reschedule //clear tournament tournamentQueueSize = 0; //schedule new tournament _scheduleTournament(); uint256 currentBank = currentTournamentBank; currentTournamentBank = 0;//nullify before sending to users //grand rewards, not susceptible to reentry attack //because of require(tournamentEndBlock <= block.number) //and require(tournamentQueueSize > 0) and currentTournamentBank == 0 uint256 incentiveReward = _grandTournamentRewards(currentBank, warriorsData, results); currentTournamentBank = nextTournamentBank; nextTournamentBank = 0; _repackToWarriorOwners(warriorsData); //emit event TournamentFinished(warriorsData, results, currentBank); return incentiveReward; } function finishTournament() external TournamentNotPaused { //make all the checks // tournament is ready to be executed require(tournamentEndBlock <= block.number); // we have participants require(tournamentQueueSize > 0); uint256 incentiveReward = _triggerFinishTournament(); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Remove all PVP contenders from PVP queue // and return all entrance fees to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllTournamentContenders() external onlyOwner TournamentPaused { //remove all pvp contenders uint256 length = tournamentQueueSize; uint256 warriorId; uint256 failedBooty; uint256 i; uint256 fee; uint256 bank = currentTournamentBank; uint256[] memory warriorsData = new uint256[](length); //get tournament warriors for(i = 0; i < length; i ++) { warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } //notify pvp listener pvpListener.tournamentFinished(warriorsData); //return entrance fee to warrior owners currentTournamentBank = 0; tournamentQueueSize = 0; for(i = length - 1; i >= 0; i --) { //return entrance fee warriorId = CryptoUtils._unpackWarriorId(warriorsData[i], 0); //compute contender entrance fee fee = bank - (bank * 10000 / (tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 + 10000)); //return entrance fee to owner failedBooty += sendBooty(warriorToOwner[warriorId], fee); //subtract fee from bank, for next use bank -= fee; } currentTournamentBank = bank; totalBooty += failedBooty; } } contract BattleProvider is Tournament { function BattleProvider(address _pvpListener, uint256 _pvpCut, uint256 _tournamentCut, uint256 _incentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public Tournament(_pvpCut, _tournamentCut, _incentiveCut, _tournamentOwnersCut, _tournamentIncentiveCut) { PVPListenerInterface candidateContract = PVPListenerInterface(_pvpListener); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPListener()); // Set the new contract address pvpListener = candidateContract; // the creator of the contract is the initial owner owner = msg.sender; } // @dev Sanity check that allows us to ensure that we are pointing to the // right BattleProvider in our setBattleProviderAddress() call. function isPVPProvider() external pure returns (bool) { return true; } function setSecondsPerBlock(uint256 secs) external onlyOwner { secondsPerBlock = secs; } } /* warrior identity generator*/ contract WarriorGenerator is Pausable, SanctuaryInterface { CryptoWarriorCore public coreContract; /* LIMITS */ uint32[19] public parameters;/* = [ uint32(10),//0_bodyColorMax3 uint32(10),//1_eyeshMax4 uint32(10),//2_mouthMax5 uint32(20),//3_heirMax6 uint32(10),//4_heirColorMax7 uint32(3),//5_armorMax8 uint32(3),//6_weaponMax9 uint32(3),//7_hatMax10 uint32(4),//8_runesMax11 uint32(1),//9_wingsMax12 uint32(10),//10_petMax13 uint32(6),//11_borderMax14 uint32(6),//12_backgroundMax15 uint32(10),//13_unique uint32(900),//14_legendary uint32(9000),//15_mythic uint32(90000),//16_rare uint32(900000),//17_uncommon uint32(0)//18_uniqueTotal ];*/ function changeParameter(uint32 _paramIndex, uint32 _value) external onlyOwner { CryptoUtils._changeParameter(_paramIndex, _value, parameters); } // / @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool){ return true; } // / @dev generate new warrior identity // / @param _heroIdentity Genes of warrior that invoked resurrection, if 0 => Demigod gene that signals to generate unique warrior // / @param _heroLevel Level of the warrior // / @_targetBlock block number from which hash will be taken // / @_perkId special perk id, like MINER(1) // / @return the identity that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256) { //only core contract can call this method require(msg.sender == address(coreContract)); return _generateIdentity(_heroIdentity, _heroLevel, _targetBlock, _perkId); } function _generateIdentity(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) internal returns(uint256){ //get memory copy, to reduce storage read requests uint32[19] memory memoryParams = parameters; //generate warrior identity uint256 identity = CryptoUtils.generateWarrior(_heroIdentity, _heroLevel, _targetBlock, _perkId, memoryParams); //validate before pushing changes to storage CryptoUtils._validateIdentity(identity, memoryParams); //push changes to storage CryptoUtils._recordWarriorData(identity, parameters); return identity; } } contract WarriorSanctuary is WarriorGenerator { uint256 internal constant SUMMONING_SICKENESS = 12 hours; uint256 internal constant RITUAL_DURATION = 15 minutes; /// @notice The payment required to use startRitual(). uint256 public ritualFee = 10 finney; uint256 public constant RITUAL_COMPENSATION = 2 finney; mapping(address => uint256) public soulCounter; // mapping(address => uint256) public ritualTimeBlock; bool public recoveryAllowed = true; event WarriorBurned(uint256 warriorId, address owner); event RitualStarted(address owner, uint256 numberOfSouls); event RitualFinished(address owner, uint256 numberOfSouls, uint256 newWarriorId); function WarriorSanctuary(address _coreContract, uint32[] _settings) public { uint256 length = _settings.length; require(length == 18); require(_settings[8] == 4);//check runes max require(_settings[10] == 10);//check pets max require(_settings[11] == 5);//check border max require(_settings[12] == 6);//check background max //setup parameters for(uint256 i = 0; i < length; i ++) { parameters[i] = _settings[i]; } //set core CryptoWarriorCore coreCondidat = CryptoWarriorCore(_coreContract); require(coreCondidat.isPVPListener()); coreContract = coreCondidat; } function recoverSouls(address[] owners, uint256[] souls, uint256[] blocks) external onlyOwner { require(recoveryAllowed); uint256 length = owners.length; require(length == souls.length && length == blocks.length); for(uint256 i = 0; i < length; i ++) { soulCounter[owners[i]] = souls[i]; ritualTimeBlock[owners[i]] = blocks[i]; } recoveryAllowed = false; } //burn warrior function burnWarrior(uint256 _warriorId) whenNotPaused external { coreContract.burnWarrior(_warriorId, msg.sender); soulCounter[msg.sender] ++; WarriorBurned(_warriorId, msg.sender); } function startRitual() whenNotPaused external payable { // Checks for payment. require(msg.value >= ritualFee); uint256 souls = soulCounter[msg.sender]; // Check that address has at least 10 burned souls require(souls >= 10); // //Check that no rituals are in progress require(ritualTimeBlock[msg.sender] == 0); ritualTimeBlock[msg.sender] = RITUAL_DURATION / coreContract.secondsPerBlock() + block.number; // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - ritualFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail if (feeExcess > 0) { msg.sender.transfer(feeExcess); } //send battle fee to beneficiary coreContract.getBeneficiary().transfer(ritualFee - RITUAL_COMPENSATION); RitualStarted(msg.sender, souls); } //arise warrior function finishRitual(address _owner) whenNotPaused external { // Check ritual time is over uint256 timeBlock = ritualTimeBlock[_owner]; require(timeBlock > 0 && timeBlock <= block.number); uint256 souls = soulCounter[_owner]; require(souls >= 10); uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0); uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock())); soulCounter[_owner] = 0; ritualTimeBlock[_owner] = 0; //send compensation msg.sender.transfer(RITUAL_COMPENSATION); RitualFinished(_owner, 10, warriorId); } function setRitualFee(uint256 _pveRitualFee) external onlyOwner { require(_pveRitualFee > RITUAL_COMPENSATION); ritualFee = _pveRitualFee; } } contract AuctionBase { uint256 public constant PRICE_CHANGE_TIME_STEP = 15 minutes; // struct Auction{ address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) internal tokenIdToAuction; uint256 public ownerCut; ERC721 public nonFungibleContract; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller); event AuctionCancelled(uint256 tokenId, address seller); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool){ return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal{ nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal{ nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal{ require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated(uint256(_tokenId), _auction.seller, _auction.startingPrice); } function _cancelAuction(uint256 _tokenId, address _seller) internal{ _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, _seller); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); nonFungibleContract.getBeneficiary().transfer(auctioneerCut); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, msg.sender, seller); return price; } function _removeAuction(uint256 _tokenId) internal{ delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool){ return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256){ uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice(_auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256){ if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed / PRICE_CHANGE_TIME_STEP * PRICE_CHANGE_TIME_STEP) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256){ return _price * ownerCut / 10000; } } contract SaleClockAuction is Pausable, AuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779); bool public isSaleClockAuction = true; uint256 public minerSaleCount; uint256[5] public lastMinerSalePrices; function SaleClockAuction(address _nftAddress, uint256 _cut) public{ require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); require(candidateContract.getBeneficiary() != address(0)); nonFungibleContract = candidateContract; } function cancelAuction(uint256 _tokenId) external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256){ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller) whenNotPaused external{ require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); AuctionBase.Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now)); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) whenNotPaused external payable{ address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (seller == nonFungibleContract.getBeneficiary()) { lastMinerSalePrices[minerSaleCount % 5] = price; minerSaleCount++; } } function averageMinerSalePrice() external view returns (uint256){ uint256 sum = 0; for (uint256 i = 0; i < 5; i++){ sum += lastMinerSalePrices[i]; } return sum / 5; } /**getAuctionsById returns packed actions data * @param tokenIds ids of tokens, whose auction's must be active * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctionsById(uint32[] tokenIds) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; auctionData = new uint256[](tokenIds.length * stepSize); uint32 tokenId; for(uint32 i = 0; i < tokenIds.length; i ++) { tokenId = tokenIds[i]; AuctionBase.Auction storage auction = tokenIdToAuction[tokenId]; require(_isOnAuction(auction)); _setTokenData(auctionData, auction, tokenId, i * stepSize); } } /**getAuctions returns packed actions data * @param fromIndex warrior index from global warrior storage (aka warriorId) * @param count Number of auction's to find, if count == 0, then exact warriorId(fromIndex) will be searched * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctions(uint32 fromIndex, uint32 count) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; if (count == 0) { AuctionBase.Auction storage auction = tokenIdToAuction[fromIndex]; require(_isOnAuction(auction)); auctionData = new uint256[](1 * stepSize); _setTokenData(auctionData, auction, fromIndex, count); return (auctionData, stepSize); } else { uint256 totalWarriors = nonFungibleContract.totalSupply(); if (totalWarriors == 0) { // Return an empty array return (new uint256[](0), stepSize); } else { uint32 totalSize = 0; uint32 tokenId; uint32 size = 0; auctionData = new uint256[](count * stepSize); for (tokenId = 0; tokenId < totalWarriors && size < count; tokenId++) { AuctionBase.Auction storage auction1 = tokenIdToAuction[tokenId]; if (_isOnAuction(auction1)) { totalSize ++; if (totalSize > fromIndex) { _setTokenData(auctionData, auction1, tokenId, size++ * stepSize);//warriorId; } } } if (size < count) { size *= stepSize; uint256[] memory repack = new uint256[](size); for(tokenId = 0; tokenId < size; tokenId++) { repack[tokenId] = auctionData[tokenId]; } return (repack, stepSize); } return (auctionData, stepSize); } } } // @dev Returns auction info for an NFT on auction. // @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return (auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt); } //pack NFT data into specified array function _setTokenData(uint256[] memory auctionData, AuctionBase.Auction storage auction, uint32 tokenId, uint32 index ) internal view { auctionData[index] = uint256(tokenId);//0 auctionData[index + 1] = uint256(auction.seller);//1 auctionData[index + 2] = uint256(auction.startingPrice);//2 auctionData[index + 3] = uint256(auction.endingPrice);//3 auctionData[index + 4] = uint256(auction.duration);//4 auctionData[index + 5] = uint256(auction.startedAt);//5 } }
Computes incentive reward for launching tournament finishTournament() _tournamentBank NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() statement in the Tournament constructor). The result of this function is always guaranteed to be <= _currentBank.
function _computeTournamentIncentiveReward(uint256 _currentBank, uint256 _incentiveCut) internal pure returns (uint256){ return _currentBank * _incentiveCut / 10000; }
5,942,420
/* Copyright 2017 Dharma Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.19; import "./DebtRegistry.sol"; import "./TermsContract.sol"; import "./TokenTransferProxy.sol"; import "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "../NonFungibleToken/contracts/ERC721.sol"; /** * The RepaymentRouter routes allowers payers to make repayments on any * given debt agreement in any given token by routing the payments to * the debt agreement's beneficiary. Additionally, the router acts * as a trusted oracle to the debt agreement's terms contract, informing * it of exactly what payments have been made in what quantity and in what token. * * Authors: Jaynti Kanani -- Github: jdkanani, Nadav Hollander -- Github: nadavhollander */ contract RepaymentRouter is Pausable { DebtRegistry public debtRegistry; TokenTransferProxy public tokenTransferProxy; enum Errors { DEBT_AGREEMENT_NONEXISTENT, PAYER_BALANCE_OR_ALLOWANCE_INSUFFICIENT, PAYER_OWNERSHIP_OR_ROUTER_APPROVAL_MISSING, ROUTER_UNAUTHORIZED_TO_REPORT_REPAYMENT } event LogRepayment( bytes32 indexed _agreementId, address indexed _payer, address indexed _beneficiary, uint _amount, address _token ); event LogError(uint8 indexed _errorId, bytes32 indexed _agreementId); /** * Constructor points the repayment router at the deployed registry contract. */ function RepaymentRouter (address _debtRegistry, address _tokenTransferProxy) public { debtRegistry = DebtRegistry(_debtRegistry); tokenTransferProxy = TokenTransferProxy(_tokenTransferProxy); } /** * Given an agreement id (synonymous to 'issuanceHash' in the debt registry), routes a repayment * of a given ERC20 token to the debt's current beneficiary, and reports the repayment * to the debt's associated terms contract. */ function repay( bytes32 agreementId, uint256 amount, address tokenAddress ) public whenNotPaused returns (uint _amountRepaid) { require(tokenAddress != address(0)); require(amount > 0); // Get registry entry and check if entry is valid address beneficiary = debtRegistry.getBeneficiary(agreementId); if (beneficiary == address(0)) { LogError(uint8(Errors.DEBT_AGREEMENT_NONEXISTENT), agreementId); return 0; } // Check payer has sufficient balance and has granted router sufficient allowance if (ERC20(tokenAddress).balanceOf(msg.sender) < amount || ERC20(tokenAddress).allowance(msg.sender, tokenTransferProxy) < amount) { LogError(uint8(Errors.PAYER_BALANCE_OR_ALLOWANCE_INSUFFICIENT), agreementId); return 0; } // Notify terms contract address termsContract = debtRegistry.getTermsContract(agreementId); if (!TermsContract(termsContract).registerRepayment( agreementId, msg.sender, beneficiary, amount, tokenAddress )) { LogError(uint8(Errors.ROUTER_UNAUTHORIZED_TO_REPORT_REPAYMENT), agreementId); return 0; } // Transfer amount to creditor require(tokenTransferProxy.transferFrom( tokenAddress, msg.sender, beneficiary, amount )); // Log event for repayment LogRepayment(agreementId, msg.sender, beneficiary, amount, tokenAddress); return amount; } }
Constructor points the repayment router at the deployed registry contract./
function RepaymentRouter (address _debtRegistry, address _tokenTransferProxy) public { debtRegistry = DebtRegistry(_debtRegistry); tokenTransferProxy = TokenTransferProxy(_tokenTransferProxy); }
6,422,864
./full_match/5/0x5e88650C4e38206addb2561cec3103Fa6C6A9bF7/sources/contracts/collections/ERC721A/extensions/ERC721ARoleBasedLockableExtension.sol
Unlocks locked token(s) to be able to transfer./
function unlock(uint256 tokenId) public virtual nonReentrant { require(hasRole(LOCKER_ROLE, msg.sender), "NOT_LOCKER_ROLE"); _unlock(tokenId); }
1,890,316
./partial_match/4/0x8Af0D8E910b23Ca0a6C0c832efA07EE494AB4346/sources/DMEX_Base.sol
send AMB bridge instruction
function sendDepositInstructionToAMBBridge(address user, address token, uint256 amount) internal { bytes4 methodSelector = DMEXXDAI(DMEX_XDAI_CONTRACT).depositTokenForUser.selector; bytes memory data = abi.encodeWithSelector(methodSelector, token, amount, user); uint256 gas = IAMB(AMBBridgeContract).maxGasPerTx(); bytes32 msgId = IAMB(AMBBridgeContract).requireToPassMessage(DMEX_XDAI_CONTRACT, data, gas); }
8,702,371
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import "./UniswapV2Library.sol"; import "../interface/IOldERC20.sol"; contract SimpleOracle { address public immutable weth; IUniswapV2Factory public uniswapV2Factory; constructor(address _weth, address factory) { weth = _weth; uniswapV2Factory = IUniswapV2Factory(factory); } function getReservesForTokenPool(address _token) public view returns (uint256 wethReserve, uint256 tokenReserve) { IUniswapV2Pair pair = IUniswapV2Pair( uniswapV2Factory.getPair(_token, weth) ); uint112 _wethReserve; uint112 _tokenReserve; // get token 0 from pair // if token 0 is provided _token if (pair.token0() == _token) { // return tokenReserve as reserve 0 and wethReserve as reserve1 (_tokenReserve, _wethReserve, ) = pair.getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); } else { // else return wethReserve as reserve 0 and tokenReserve as reserve1 (_wethReserve, _tokenReserve, ) = IUniswapV2Pair(pair).getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); } require(_tokenReserve != 0, "token reserves cannot be zero"); require(_wethReserve != 0, "weth reserves cannot be zero"); } function getTokenPrice(address tbnTokenAddress, address paymentTokenAddress) external view returns (uint256) { /** Calculation of price - get common base between reserves and divide out for exchange rate */ require( tbnTokenAddress != paymentTokenAddress, "Cannot get price for same token" ); // Get the reserves ( uint256 tbnWETHReserves, uint256 tbnTokenReserves ) = getReservesForTokenPool(tbnTokenAddress); ( uint256 paymentWETHReserves, uint256 paymentTokenReserves ) = getReservesForTokenPool(paymentTokenAddress); // get the decimals uint8 tbnTokenDecimals = IOldERC20(tbnTokenAddress).decimals(); uint8 paymentTokenDecimals = IOldERC20(paymentTokenAddress).decimals(); // tbnTokenPrice / paymentTokenPrice if (paymentTokenDecimals < tbnTokenDecimals) { uint8 decimalDiff = tbnTokenDecimals - paymentTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves * (10**decimalDiff)) / (paymentWETHReserves * tbnTokenReserves); } else if (tbnTokenDecimals < paymentTokenDecimals) { uint8 decimalDiff = paymentTokenDecimals - tbnTokenDecimals; return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves * (10**decimalDiff)); } else { return (1 ether * tbnWETHReserves * paymentTokenReserves) / (paymentWETHReserves * tbnTokenReserves); } } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library UniswapV2Library { using SafeMath for uint256; // 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, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // fetches and sorts the reserves for a pair function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair( pairFor(factory, tokenA, tokenB) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 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, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves( factory, path[i - 1], path[i] ); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; contract IOldERC20 { function decimals() public view virtual returns (uint8) {} } // 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; } }
get token 0 from pair if token 0 is provided _token return tokenReserve as reserve 0 and wethReserve as reserve1 else return wethReserve as reserve 0 and tokenReserve as reserve1
function getReservesForTokenPool(address _token) public view returns (uint256 wethReserve, uint256 tokenReserve) { IUniswapV2Pair pair = IUniswapV2Pair( uniswapV2Factory.getPair(_token, weth) ); uint112 _wethReserve; uint112 _tokenReserve; if (pair.token0() == _token) { (_tokenReserve, _wethReserve, ) = pair.getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); (_wethReserve, _tokenReserve, ) = IUniswapV2Pair(pair).getReserves(); wethReserve = uint256(_wethReserve); tokenReserve = uint256(_tokenReserve); } require(_tokenReserve != 0, "token reserves cannot be zero"); require(_wethReserve != 0, "weth reserves cannot be zero"); }
10,450,594
./full_match/4/0x0A87021D82453AB0B18a375aFfdB8C689e05A182/sources/sirtoken3.sol
Get account token balance. account_ address Requred: - validAddress(account_) non 0 address return uint256 account balance/
function balanceOf( address account_ ) public view virtual override returns (uint256) { return _balances[account_]; }
12,424,915
pragma solidity ^0.5.3; contract Freezable { bool public frozen; address public freezer; // onlyFreezer functions can only be called by the specified `freezer` address modifier onlyFreezer() { require(msg.sender == freezer); _; } // onlyWhenNotFrozen functions can only be called when `frozen` is false, otherwise they will // revert. modifier onlyWhenNotFrozen() { require(!frozen); _; } /** * @notice Sets the address that is allowed to freeze/unfreeze the contract. * @param _freezer The address that is allowed to freeze/unfree the contract * @dev This function is `internal` and leaves its permissioning up to the inheriting contract. */ function _setFreezer(address _freezer) internal { freezer = _freezer; } /** * @notice Freezes the contract, disabling `onlyWhenNotFrozen` functions. */ function freeze() external onlyFreezer { frozen = true; } /** * @notice Unreezes the contract, enabling `onlyWhenNotFrozen` functions. */ function unfreeze() external onlyFreezer { frozen = false; } }
Unreezes the contract, enabling `onlyWhenNotFrozen` functions./
function unfreeze() external onlyFreezer { frozen = false; }
12,640,284
./partial_match/56/0xf4FFdD2758c6c76D38Ad0c12ef260B9467687E51/sources/PlatiniumFinance.sol
Transfers ownership of the contract to a new account (`newOwner`)./
function _transferOwnership(address newOwner) internal { emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
11,209,845
pragma solidity ^0.5.13; import "./ItemFactory.sol"; /** * @title ProShop * @notice Main contract for sales side of the In-game Pro Shop System */ contract ProShop is ItemFactory { /** * @notice emitted upon the withdrawal of a Shop's balance */ event ShopBalanceWithdrawn(uint256 shopId, uint256 amount); /** * @notice emitted upon the withdrawal of the franchise's balance */ event FranchiseBalanceWithdrawn(uint256 amount); constructor() public { franchiseFeePercent = 0; // Percentage of each sale going to the franchise owner } /** * @notice Set the address of the StockRoom contract */ function setStockRoomContractAddress(address _address) external onlySysAdmin { StockRoomInterface candidateContract = StockRoomInterface(_address); // Verify that we have the appropriate address require(candidateContract.isStockRoom()); // Set the new contract address stockRoom = candidateContract; } /** * @notice Allow a shop owner to withdraw the accumulated balance of their shop, if any */ function withdrawShopBalance(uint256 _shopId) external whenNotPaused onlyShopOwner(_shopId) { uint amount = shopBalances[_shopId]; address self = address(this); require(amount > 0, "No shop balance to withdraw."); require(amount <= self.balance, "Insufficient contract balance."); shopBalances[_shopId] = 0; msg.sender.transfer(amount); emit ShopBalanceWithdrawn(_shopId, amount); } /** * @notice Allow the franchise owner to withdraw their accumulated balance, if any */ function withdrawFranchiseBalance() external whenNotPaused onlyFranchiseOwner { uint amount = franchiseBalance; require(amount > 0, "No franchise balance to withdraw."); address self = address(this); require(amount <= self.balance, "Insufficient contract balance."); franchiseBalance = 0; msg.sender.transfer(amount); emit FranchiseBalanceWithdrawn(amount); } /** * @notice Allow a shop owner to check the accumulated balance of their shop in Ether or Shop fiat */ function checkShopBalance(uint256 _shopId, bool _inFiat) external view onlyShopOwner(_shopId) returns(uint256) { uint256 balance = shopBalances[_shopId]; return (balance > 0 && _inFiat) ? stockRoom.convertEtherToShopFiat(_shopId, balance) : balance; } /** * @notice Allow the franchise owner to check their accumulated balance in Ether or franchise fiat */ function checkFranchiseBalance(bool _inFiat) external view onlyFranchiseOwner() returns(uint256) { return (franchiseBalance > 0 && _inFiat) ? stockRoom.convertEtherToFranchiseFiat(franchiseBalance) : franchiseBalance; } // @notice Get the list of Item Ids associated with a given Owner function getItemIds(address _owner) external view returns (uint[] memory) { return ownedItems[_owner]; } /** * @notice Get the count of minted Items associated with a given Shop */ function getShopItemCount(uint256 _shopId) external view returns (uint256) { return shopItems[_shopId].length; } /** * @notice Get the count of minted Items associated with a given SKU */ function getSKUItemCount(uint256 _skuId) external view returns (uint256) { return skuItems[_skuId].length; } /** * @notice Get the count of Items associated with a given Owner */ function getOwnerItemCount(address _owner) external view returns (uint256) { return ownedItems[_owner].length; } }
Get the count of Items associated with a given Owner/
function getOwnerItemCount(address _owner) external view returns (uint256) { return ownedItems[_owner].length; }
12,801,019
pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @title Checkpointing - Library to handle a historic set of numeric values */ library Checkpointing { uint256 private constant MAX_UINT192 = uint256(uint192(-1)); string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG"; string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE"; /** * @dev To specify a value at a given point in time, we need to store two values: * - `time`: unit-time value to denote the first time when a value was registered * - `value`: a positive numeric value to registered at a given point in time * * Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used * for it like block numbers, terms, etc. */ struct Checkpoint { uint64 time; uint192 value; } /** * @dev A history simply denotes a list of checkpoints */ struct History { Checkpoint[] history; } /** * @dev Add a new value to a history for a given point in time. This function does not allow to add values previous * to the latest registered value, if the value willing to add corresponds to the latest registered value, it * will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function add(History storage self, uint64 _time, uint256 _value) internal { require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG); _add192(self, _time, uint192(_value)); } /** * @dev Fetch the latest registered value of history, it will return zero if there was no value registered * @param self Checkpoints history to be queried */ function getLast(History storage self) internal view returns (uint256) { uint256 length = self.history.length; if (length > 0) { return uint256(self.history[length - 1].value); } return 0; } /** * @dev Fetch the most recent registered past value of a history based on a given point in time that is not known * how recent it is beforehand. It will return zero if there is no registered value or if given time is * previous to the first registered value. * It uses a binary search. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function get(History storage self, uint64 _time) internal view returns (uint256) { return _binarySearch(self, _time); } /** * @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero * if there is no registered value or if given time is previous to the first registered value. * It uses a linear search starting from the end. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function getRecent(History storage self, uint64 _time) internal view returns (uint256) { return _backwardsLinearSearch(self, _time); } /** * @dev Private function to add a new value to a history for a given point in time. This function does not allow to * add values previous to the latest registered value, if the value willing to add corresponds to the latest * registered value, it will be updated. * @param self Checkpoints history to be altered * @param _time Point in time to register the given value * @param _value Numeric value to be registered at the given point in time */ function _add192(History storage self, uint64 _time, uint192 _value) private { uint256 length = self.history.length; if (length == 0 || self.history[self.history.length - 1].time < _time) { // If there was no value registered or the given point in time is after the latest registered value, // we can insert it to the history directly. self.history.push(Checkpoint(_time, _value)); } else { // If the point in time given for the new value is not after the latest registered value, we must ensure // we are only trying to update the latest value, otherwise we would be changing past data. Checkpoint storage currentCheckpoint = self.history[length - 1]; require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE); currentCheckpoint.value = _value; } } /** * @dev Private function to execute a backwards linear search to find the most recent registered past value of a * history based on a given point in time. It will return zero if there is no registered value or if given time * is previous to the first registered value. Note that this function will be more suitable when we already know * that the time used to index the search is recent in the given history. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } uint256 index = length - 1; Checkpoint storage checkpoint = self.history[index]; while (index > 0 && checkpoint.time > _time) { index--; checkpoint = self.history[index]; } return checkpoint.time > _time ? 0 : uint256(checkpoint.value); } /** * @dev Private function execute a binary search to find the most recent registered past value of a history based on * a given point in time. It will return zero if there is no registered value or if given time is previous to * the first registered value. Note that this function will be more suitable when don't know how recent the * time used to index may be. * @param self Checkpoints history to be queried * @param _time Point in time to query the most recent registered past value of */ function _binarySearch(History storage self, uint64 _time) private view returns (uint256) { // If there was no value registered for the given history return simply zero uint256 length = self.history.length; if (length == 0) { return 0; } // If the requested time is equal to or after the time of the latest registered value, return latest value uint256 lastIndex = length - 1; if (_time >= self.history[lastIndex].time) { return uint256(self.history[lastIndex].value); } // If the requested time is previous to the first registered value, return zero to denote missing checkpoint if (_time < self.history[0].time) { return 0; } // Execute a binary search between the checkpointed times of the history uint256 low = 0; uint256 high = lastIndex; while (high > low) { // No need for SafeMath: for this to overflow array size should be ~2^255 uint256 mid = (high + low + 1) / 2; Checkpoint storage checkpoint = self.history[mid]; uint64 midTime = checkpoint.time; if (_time > midTime) { low = mid; } else if (_time < midTime) { // No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1 high = mid - 1; } else { return uint256(checkpoint.value); } } return uint256(self.history[low].value); } } library Uint256Helpers { uint256 private constant MAX_UINT8 = uint8(-1); uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG"; string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint8(uint256 a) internal pure returns (uint8) { require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG); return uint8(a); } function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG); return uint64(a); } } /** * @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"); } } /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } /* * @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 is Initializable { // 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; } } contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } /** * @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"); } } } /** * @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); } /** * @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 {ERC20Mintable}. * * 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 Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 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 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 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "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 { require(account != address(0), "ERC20: mint to the zero address"); _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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } uint256[50] private ______gap; } /** * @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; } } // Interface for interaction with Wormhole v2 TokenBridge // https://github.com/certusone/wormhole/blob/7e2cf1f9818099c63c21d101afbfedb1903ee9ba/ethereum/contracts/bridge/Bridge.sol#L93 interface Wormhole { function transferTokens( address token, uint256 amount, uint16 recipientChain, bytes32 recipient, uint256 arbiterFee, uint32 nonce ) external; } /** * Wrapper around OpenZeppelin's Initializable contract. * Exposes initialized state management to ensure logic contract functions cannot be called before initialization. * This is needed because OZ's Initializable contract no longer exposes initialized state variable. * https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol */ contract InitializableV2 is Initializable { bool private isInitialized; string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized"; /** * @notice wrapper function around parent contract Initializable's `initializable` modifier * initializable modifier ensures this function can only be called once by each deployed child contract * sets isInitialized flag to true to which is used by _requireIsInitialized() */ function initialize() public initializer { isInitialized = true; } /** * @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure * contract is initialized before functions can be called. */ function _requireIsInitialized() internal view { require(isInitialized == true, ERROR_NOT_INITIALIZED); } /** * @notice Exposes isInitialized bool var to child contracts with read-only access */ function _isInitialized() internal view returns (bool) { return isInitialized; } } contract Staking is InitializableV2 { using SafeMath for uint256; using Uint256Helpers for uint256; using Checkpointing for Checkpointing.History; using SafeERC20 for ERC20; string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract"; string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed"; string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance"; string private constant ERROR_ONLY_DELEGATE_MANAGER = ( "Staking: Only callable from DelegateManager" ); string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = ( "Staking: Only callable from ServiceProviderFactory" ); address private governanceAddress; address private claimsManagerAddress; address private delegateManagerAddress; address private serviceProviderFactoryAddress; /// @dev stores the history of staking and claims for a given address struct Account { Checkpointing.History stakedHistory; Checkpointing.History claimHistory; } /// @dev ERC-20 token that will be used to stake with ERC20 internal stakingToken; /// @dev maps addresses to staking and claims history mapping (address => Account) internal accounts; /// @dev total staked tokens at a given block Checkpointing.History internal totalStakedHistory; event Staked(address indexed user, uint256 amount, uint256 total); event Unstaked(address indexed user, uint256 amount, uint256 total); event Slashed(address indexed user, uint256 amount, uint256 total); /** * @notice Function to initialize the contract * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @param _tokenAddress - address of ERC20 token that will be staked * @param _governanceAddress - address for Governance proxy contract */ function initialize( address _tokenAddress, address _governanceAddress ) public initializer { require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT); stakingToken = ERC20(_tokenAddress); _updateGovernanceAddress(_governanceAddress); InitializableV2.initialize(); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); } /** * @notice Set the ClaimsManaager address * @dev Only callable by Governance address * @param _claimsManager - address for new ClaimsManaager contract */ function setClaimsManagerAddress(address _claimsManager) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManager; } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _delegateManager - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManager) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _delegateManager; } /* External functions */ /** * @notice Funds `_amount` of tokens from ClaimsManager to target account * @param _amount - amount of rewards to add to stake * @param _stakerAccount - address of staker */ function stakeRewards(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress, "Staking: Only callable from ClaimsManager" ); _stakeFor(_stakerAccount, msg.sender, _amount); this.updateClaimHistory(_amount, _stakerAccount); } /** * @notice Update claim history by adding an event to the claim history * @param _amount - amount to add to claim history * @param _stakerAccount - address of staker */ function updateClaimHistory(uint256 _amount, address _stakerAccount) external { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( msg.sender == claimsManagerAddress || msg.sender == address(this), "Staking: Only callable from ClaimsManager or Staking.sol" ); // Update claim history even if no value claimed accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount); } /** * @notice Slashes `_amount` tokens from _slashAddress * @dev Callable from DelegateManager * @param _amount - Number of tokens slashed * @param _slashAddress - Address being slashed */ function slash( uint256 _amount, address _slashAddress ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); // Burn slashed tokens from account _burnFor(_slashAddress, _amount); emit Slashed( _slashAddress, _amount, totalStakedFor(_slashAddress) ); } /** * @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress` * @param _accountAddress - The final staker of the tokens * @param _amount - Number of tokens staked */ function stakeFor( address _accountAddress, uint256 _amount ) external { _requireIsInitialized(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == serviceProviderFactoryAddress, ERROR_ONLY_SERVICE_PROVIDER_FACTORY ); _stakeFor( _accountAddress, _accountAddress, _amount ); } /** * @notice Unstakes `_amount` tokens, returning them to the desired account. * @param _accountAddress - Account unstaked for, and token recipient * @param _amount - Number of tokens staked */ function unstakeFor( address _accountAddress, uint256 _amount ) external { _requireIsInitialized(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == serviceProviderFactoryAddress, ERROR_ONLY_SERVICE_PROVIDER_FACTORY ); _unstakeFor( _accountAddress, _accountAddress, _amount ); } /** * @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`, only callable by DelegateManager * @param _accountAddress - The final staker of the tokens * @param _delegatorAddress - Address from which to transfer tokens * @param _amount - Number of tokens staked */ function delegateStakeFor( address _accountAddress, address _delegatorAddress, uint256 _amount ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); _stakeFor( _accountAddress, _delegatorAddress, _amount); } /** * @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`, only callable by DelegateManager * @param _accountAddress - The staker of the tokens * @param _delegatorAddress - Address from which to transfer tokens * @param _amount - Number of tokens unstaked */ function undelegateStakeFor( address _accountAddress, address _delegatorAddress, uint256 _amount ) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, ERROR_ONLY_DELEGATE_MANAGER ); _unstakeFor( _accountAddress, _delegatorAddress, _amount); } /** * @notice Get the token used by the contract for staking and locking * @return The token used by the contract for staking and locking */ function token() external view returns (address) { _requireIsInitialized(); return address(stakingToken); } /** * @notice Check whether it supports history of stakes * @return Always true */ function supportsHistory() external view returns (bool) { _requireIsInitialized(); return true; } /** * @notice Get last time `_accountAddress` modified its staked balance * @param _accountAddress - Account requesting for * @return Last block number when account's balance was modified */ function lastStakedFor(address _accountAddress) external view returns (uint256) { _requireIsInitialized(); uint256 length = accounts[_accountAddress].stakedHistory.history.length; if (length > 0) { return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time); } return 0; } /** * @notice Get last time `_accountAddress` claimed a staking reward * @param _accountAddress - Account requesting for * @return Last block number when claim requested */ function lastClaimedFor(address _accountAddress) external view returns (uint256) { _requireIsInitialized(); uint256 length = accounts[_accountAddress].claimHistory.history.length; if (length > 0) { return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time); } return 0; } /** * @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber` * @param _accountAddress - Account requesting for * @param _blockNumber - Block number at which we are requesting * @return The amount of tokens staked by the account at the given block number */ function totalStakedForAt( address _accountAddress, uint256 _blockNumber ) external view returns (uint256) { _requireIsInitialized(); return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64()); } /** * @notice Get the total amount of tokens staked by all users at block number `_blockNumber` * @param _blockNumber - Block number at which we are requesting * @return The amount of tokens staked at the given block number */ function totalStakedAt(uint256 _blockNumber) external view returns (uint256) { _requireIsInitialized(); return totalStakedHistory.get(_blockNumber.toUint64()); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /** * @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress is currently a valid staker with a non-zero stake * @param _accountAddress - Account requesting for * @return Boolean indicating whether account is a staker */ function isStaker(address _accountAddress) external view returns (bool) { _requireIsInitialized(); return totalStakedFor(_accountAddress) > 0; } /* Public functions */ /** * @notice Get the amount of tokens staked by `_accountAddress` * @param _accountAddress - The owner of the tokens * @return The amount of tokens staked by the given account */ function totalStakedFor(address _accountAddress) public view returns (uint256) { _requireIsInitialized(); // we assume it's not possible to stake in the future return accounts[_accountAddress].stakedHistory.getLast(); } /** * @notice Get the total amount of tokens staked by all users * @return The total amount of tokens staked by all users */ function totalStaked() public view returns (uint256) { _requireIsInitialized(); // we assume it's not possible to stake in the future return totalStakedHistory.getLast(); } // ========================================= Internal Functions ========================================= /** * @notice Adds stake from a transfer account to the stake account * @param _stakeAccount - Account that funds will be staked for * @param _transferAccount - Account that funds will be transferred from * @param _amount - amount to stake */ function _stakeFor( address _stakeAccount, address _transferAccount, uint256 _amount ) internal { // staking 0 tokens is invalid require(_amount > 0, ERROR_AMOUNT_ZERO); // Checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, true); // checkpoint total supply _modifyTotalStaked(_amount, true); // pull tokens into Staking contract stakingToken.safeTransferFrom(_transferAccount, address(this), _amount); emit Staked( _stakeAccount, _amount, totalStakedFor(_stakeAccount)); } /** * @notice Unstakes tokens from a stake account to a transfer account * @param _stakeAccount - Account that staked funds will be transferred from * @param _transferAccount - Account that funds will be transferred to * @param _amount - amount to unstake */ function _unstakeFor( address _stakeAccount, address _transferAccount, uint256 _amount ) internal { require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // transfer tokens stakingToken.safeTransfer(_transferAccount, _amount); emit Unstaked( _stakeAccount, _amount, totalStakedFor(_stakeAccount) ); } /** * @notice Burn tokens for a given staker * @dev Called when slash occurs * @param _stakeAccount - Account for which funds will be burned * @param _amount - amount to burn */ function _burnFor(address _stakeAccount, uint256 _amount) internal { // burning zero tokens is not allowed require(_amount > 0, ERROR_AMOUNT_ZERO); // checkpoint updated staking balance _modifyStakeBalance(_stakeAccount, _amount, false); // checkpoint total supply _modifyTotalStaked(_amount, false); // burn ERC20Burnable(address(stakingToken)).burn(_amount); /** No event emitted since token.burn() call already emits a Transfer event */ } /** * @notice Increase or decrease the staked balance for an account * @param _accountAddress - Account to modify * @param _by - amount to modify * @param _increase - true if increase in stake, false if decrease */ function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal { uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast(); uint256 newStake; if (_increase) { newStake = currentInternalStake.add(_by); } else { require( currentInternalStake >= _by, "Staking: Cannot decrease greater than current balance"); newStake = currentInternalStake.sub(_by); } // add new value to account history accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake); } /** * @notice Increase or decrease the staked balance across all accounts * @param _by - amount to modify * @param _increase - true if increase in stake, false if decrease */ function _modifyTotalStaked(uint256 _by, bool _increase) internal { uint256 currentStake = totalStaked(); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history totalStakedHistory.add(block.number.toUint64(), newStake); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "Staking: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } // ========================================= Private Functions ========================================= function _requireClaimsManagerAddressIsSet() private view { require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set"); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "Staking: delegateManagerAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "Staking: serviceProviderFactoryAddress is not set" ); } } contract ServiceTypeManager is InitializableV2 { address governanceAddress; string private constant ERROR_ONLY_GOVERNANCE = ( "ServiceTypeManager: Only callable by Governance contract" ); /** * @dev - mapping of serviceType - serviceTypeVersion * Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"] */ mapping(bytes32 => bytes32[]) private serviceTypeVersions; /** * @dev - mapping of serviceType - < serviceTypeVersion, isValid > * Example - "discovery-provider" - <"0.0.1", true> */ mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo; /// @dev List of valid service types bytes32[] private validServiceTypes; /// @dev Struct representing service type info struct ServiceTypeInfo { bool isValid; uint256 minStake; uint256 maxStake; } /// @dev mapping of service type info mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo; event SetServiceVersion( bytes32 indexed _serviceType, bytes32 indexed _serviceVersion ); event ServiceTypeAdded( bytes32 indexed _serviceType, uint256 indexed _serviceTypeMin, uint256 indexed _serviceTypeMax ); event ServiceTypeRemoved(bytes32 indexed _serviceType); /** * @notice Function to initialize the contract * @param _governanceAddress - Governance proxy address */ function initialize(address _governanceAddress) public initializer { _updateGovernanceAddress(_governanceAddress); InitializableV2.initialize(); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); } // ========================================= Service Type Logic ========================================= /** * @notice Add a new service type * @param _serviceType - type of service to add * @param _serviceTypeMin - minimum stake for service type * @param _serviceTypeMax - maximum stake for service type */ function addServiceType( bytes32 _serviceType, uint256 _serviceTypeMin, uint256 _serviceTypeMax ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); require( !this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Already known service type" ); require( _serviceTypeMax > _serviceTypeMin, "ServiceTypeManager: Max stake must be non-zero and greater than min stake" ); // Ensure serviceType cannot be re-added if it previously existed and was removed // stored maxStake > 0 means it was previously added and removed require( serviceTypeInfo[_serviceType].maxStake == 0, "ServiceTypeManager: Cannot re-add serviceType after it was removed." ); validServiceTypes.push(_serviceType); serviceTypeInfo[_serviceType] = ServiceTypeInfo({ isValid: true, minStake: _serviceTypeMin, maxStake: _serviceTypeMax }); emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax); } /** * @notice Remove an existing service type * @param _serviceType - name of service type to remove */ function removeServiceType(bytes32 _serviceType) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); uint256 serviceIndex = 0; bool foundService = false; for (uint256 i = 0; i < validServiceTypes.length; i ++) { if (validServiceTypes[i] == _serviceType) { serviceIndex = i; foundService = true; break; } } require(foundService == true, "ServiceTypeManager: Invalid service type, not found"); // Overwrite service index uint256 lastIndex = validServiceTypes.length - 1; validServiceTypes[serviceIndex] = validServiceTypes[lastIndex]; validServiceTypes.length--; // Mark as invalid serviceTypeInfo[_serviceType].isValid = false; // Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added emit ServiceTypeRemoved(_serviceType); } /** * @notice Get isValid, min and max stake for a given service type * @param _serviceType - type of service * @return isValid, min and max stake for type */ function getServiceTypeInfo(bytes32 _serviceType) external view returns (bool isValid, uint256 minStake, uint256 maxStake) { _requireIsInitialized(); return ( serviceTypeInfo[_serviceType].isValid, serviceTypeInfo[_serviceType].minStake, serviceTypeInfo[_serviceType].maxStake ); } /** * @notice Get list of valid service types */ function getValidServiceTypes() external view returns (bytes32[] memory) { _requireIsInitialized(); return validServiceTypes; } /** * @notice Return indicating whether this is a valid service type */ function serviceTypeIsValid(bytes32 _serviceType) external view returns (bool) { _requireIsInitialized(); return serviceTypeInfo[_serviceType].isValid; } // ========================================= Service Version Logic ========================================= /** * @notice Add new version for a serviceType * @param _serviceType - type of service * @param _serviceVersion - new version of service to add */ function setServiceVersion( bytes32 _serviceType, bytes32 _serviceVersion ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type"); require( serviceTypeVersionInfo[_serviceType][_serviceVersion] == false, "ServiceTypeManager: Already registered" ); // Update array of known versions for type serviceTypeVersions[_serviceType].push(_serviceVersion); // Update status for this specific service version serviceTypeVersionInfo[_serviceType][_serviceVersion] = true; emit SetServiceVersion(_serviceType, _serviceVersion); } /** * @notice Get a version for a service type given it's index * @param _serviceType - type of service * @param _versionIndex - index in list of service versions * @return bytes32 value for serviceVersion */ function getVersion(bytes32 _serviceType, uint256 _versionIndex) external view returns (bytes32) { _requireIsInitialized(); require( serviceTypeVersions[_serviceType].length > _versionIndex, "ServiceTypeManager: No registered version of serviceType" ); return (serviceTypeVersions[_serviceType][_versionIndex]); } /** * @notice Get curent version for a service type * @param _serviceType - type of service * @return Returns current version of service */ function getCurrentVersion(bytes32 _serviceType) external view returns (bytes32) { _requireIsInitialized(); require( serviceTypeVersions[_serviceType].length >= 1, "ServiceTypeManager: No registered version of serviceType" ); uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1; return (serviceTypeVersions[_serviceType][latestVersionIndex]); } /** * @notice Get total number of versions for a service type * @param _serviceType - type of service */ function getNumberOfVersions(bytes32 _serviceType) external view returns (uint256) { _requireIsInitialized(); return serviceTypeVersions[_serviceType].length; } /** * @notice Return boolean indicating whether given version is valid for given type * @param _serviceType - type of service * @param _serviceVersion - version of service to check */ function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion) external view returns (bool) { _requireIsInitialized(); return serviceTypeVersionInfo[_serviceType][_serviceVersion]; } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ServiceTypeManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } } /// @notice ERC20 imported via Staking.sol /// @notice SafeERC20 imported via Staking.sol /// @notice Governance imported via Staking.sol /// @notice SafeMath imported via ServiceProviderFactory.sol /** * Designed to automate claim funding, minting tokens as necessary * @notice - will call InitializableV2 constructor */ contract ClaimsManager is InitializableV2 { using SafeMath for uint256; using SafeERC20 for ERC20; string private constant ERROR_ONLY_GOVERNANCE = ( "ClaimsManager: Only callable by Governance contract" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private delegateManagerAddress; /** * @notice - Minimum number of blocks between funding rounds * 604800 seconds / week * Avg block time - 13s * 604800 / 13 = 46523.0769231 blocks */ uint256 private fundingRoundBlockDiff; /** * @notice - Configures the current funding amount per round * Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year * = 70,000,000/365*7 (year is slightly more than a week) * = 1342465.75342 new AUDS per week * = 1342465753420000000000000 new wei units per week * @dev - Past a certain block height, this schedule will be updated * - Logic determining schedule will be sourced from an external contract */ uint256 private fundingAmount; // Denotes current round uint256 private roundNumber; // Staking contract ref ERC20Mintable private audiusToken; /// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start address private communityPoolAddress; /// @dev - Reward amount transferred to communityPoolAddress at funding round start uint256 private recurringCommunityFundingAmount; // Struct representing round state // 1) Block at which round was funded // 2) Total funded for this round // 3) Total claimed in round struct Round { uint256 fundedBlock; uint256 fundedAmount; uint256 totalClaimedInRound; } // Current round information Round private currentRound; event RoundInitiated( uint256 indexed _blockNumber, uint256 indexed _roundNumber, uint256 indexed _fundAmount ); event ClaimProcessed( address indexed _claimer, uint256 indexed _rewards, uint256 _oldTotal, uint256 indexed _newTotal ); event CommunityRewardsTransferred( address indexed _transferAddress, uint256 indexed _amount ); event FundingAmountUpdated(uint256 indexed _amount); event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress); event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount); event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - address for Governance proxy contract */ function initialize( address _tokenAddress, address _governanceAddress ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); fundingRoundBlockDiff = 46523; fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS roundNumber = 0; currentRound = Round({ fundedBlock: 0, fundedAmount: 0, totalClaimedInRound: 0 }); // Community pool funding amount and address initialized to zero recurringCommunityFundingAmount = 0; communityPoolAddress = address(0x0); InitializableV2.initialize(); } /// @notice Get the duration of a funding round in blocks function getFundingRoundBlockDiff() external view returns (uint256) { _requireIsInitialized(); return fundingRoundBlockDiff; } /// @notice Get the last block where a funding round was initiated function getLastFundedBlock() external view returns (uint256) { _requireIsInitialized(); return currentRound.fundedBlock; } /// @notice Get the amount funded per round in wei function getFundsPerRound() external view returns (uint256) { _requireIsInitialized(); return fundingAmount; } /// @notice Get the total amount claimed in the current round function getTotalClaimedInRound() external view returns (uint256) { _requireIsInitialized(); return currentRound.totalClaimedInRound; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /** * @notice Get the Staking address */ function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /** * @notice Get the community pool address */ function getCommunityPoolAddress() external view returns (address) { _requireIsInitialized(); return communityPoolAddress; } /** * @notice Get the community funding amount */ function getRecurringCommunityFundingAmount() external view returns (uint256) { _requireIsInitialized(); return recurringCommunityFundingAmount; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _serviceProviderFactoryAddress; emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress); } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _delegateManagerAddress - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _delegateManagerAddress; emit DelegateManagerAddressUpdated(_delegateManagerAddress); } /** * @notice Start a new funding round * @dev Permissioned to be callable by stakers or governance contract */ function initiateRound() external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff, "ClaimsManager: Required block difference not met" ); currentRound = Round({ fundedBlock: block.number, fundedAmount: fundingAmount, totalClaimedInRound: 0 }); roundNumber = roundNumber.add(1); /* * Transfer community funding amount to community pool address, if set */ if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) { // ERC20Mintable always returns true audiusToken.mint(address(this), recurringCommunityFundingAmount); // Approve transfer to community pool address audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount); // Transfer to community pool address ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount); emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount); } emit RoundInitiated( currentRound.fundedBlock, roundNumber, currentRound.fundedAmount ); } /** * @notice Mints and stakes tokens on behalf of ServiceProvider + delegators * @dev Callable through DelegateManager by Service Provider * @param _claimer - service provider address * @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider * @return minted rewards for this claimer */ function processClaim( address _claimer, uint256 _totalLockedForSP ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require( msg.sender == delegateManagerAddress, "ClaimsManager: ProcessClaim only accessible to DelegateManager" ); Staking stakingContract = Staking(stakingAddress); // Prevent duplicate claim uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer); require( lastUserClaimBlock <= currentRound.fundedBlock, "ClaimsManager: Claim already processed for user" ); uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt( _claimer, currentRound.fundedBlock); (,,bool withinBounds,,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer) ); // Once they claim the zero reward amount, stake can be modified once again // Subtract total locked amount for SP from stake at fund block uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP); uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock); // Calculate claimer rewards uint256 rewardsForClaimer = ( totalActiveClaimerStake.mul(fundingAmount) ).div(totalStakedAtFundBlock); // For a claimer violating bounds, no new tokens are minted // Claim history is marked to zero and function is short-circuited // Total rewards can be zero if all stake is currently locked up if (!withinBounds || rewardsForClaimer == 0) { stakingContract.updateClaimHistory(0, _claimer); emit ClaimProcessed( _claimer, 0, totalStakedAtFundBlockForClaimer, totalActiveClaimerStake ); return 0; } // ERC20Mintable always returns true audiusToken.mint(address(this), rewardsForClaimer); // Approve transfer to staking address for claimer rewards // ERC20 always returns true audiusToken.approve(stakingAddress, rewardsForClaimer); // Transfer rewards stakingContract.stakeRewards(rewardsForClaimer, _claimer); // Update round claim value currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer); // Update round claim value uint256 newTotal = stakingContract.totalStakedFor(_claimer); emit ClaimProcessed( _claimer, rewardsForClaimer, totalStakedAtFundBlockForClaimer, newTotal ); return rewardsForClaimer; } /** * @notice Modify funding amount per round * @param _newAmount - new amount to fund per round in wei */ function updateFundingAmount(uint256 _newAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); fundingAmount = _newAmount; emit FundingAmountUpdated(_newAmount); } /** * @notice Returns boolean indicating whether a claim is considered pending * @dev Note that an address with no endpoints can never have a pending claim * @param _sp - address of the service provider to check * @return true if eligible for claim, false if not */ function claimPending(address _sp) external view returns (bool) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp); (,,,uint256 numEndpoints,,) = ( ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp) ); return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0); } /** * @notice Modify minimum block difference between funding rounds * @param _newFundingRoundBlockDiff - new min block difference to set */ function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff); fundingRoundBlockDiff = _newFundingRoundBlockDiff; } /** * @notice Modify community funding amound for each round * @param _newRecurringCommunityFundingAmount - new reward amount transferred to * communityPoolAddress at funding round start */ function updateRecurringCommunityFundingAmount( uint256 _newRecurringCommunityFundingAmount ) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount; emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount); } /** * @notice Modify community pool address * @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount * is transferred at funding round start */ function updateCommunityPoolAddress(address _newCommunityPoolAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); communityPoolAddress = _newCommunityPoolAddress; emit CommunityPoolAddressUpdated(_newCommunityPoolAddress); } // ========================================= Private Functions ========================================= /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) private { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ClaimsManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } function _requireStakingAddressIsSet() private view { require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set"); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "ClaimsManager: delegateManagerAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "ClaimsManager: serviceProviderFactoryAddress is not set" ); } } /// @notice Governance imported via Staking.sol contract ServiceProviderFactory is InitializableV2 { using SafeMath for uint256; /// @dev - denominator for deployer cut calculations /// @dev - user values are intended to be x/DEPLOYER_CUT_BASE uint256 private constant DEPLOYER_CUT_BASE = 100; string private constant ERROR_ONLY_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Governance contract" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "ServiceProviderFactory: Only callable by Service Provider or Governance" ); address private stakingAddress; address private delegateManagerAddress; address private governanceAddress; address private serviceTypeManagerAddress; address private claimsManagerAddress; /// @notice Period in blocks that a decrease stake operation is delayed. /// Must be greater than governance votingPeriod + executionDelay in order to /// prevent pre-emptive withdrawal in anticipation of a slash proposal uint256 private decreaseStakeLockupDuration; /// @notice Period in blocks that an update deployer cut operation is delayed. /// Must be greater than funding round block diff in order /// to prevent manipulation around a funding round uint256 private deployerCutLockupDuration; /// @dev - Stores following entities /// 1) Directly staked amount by SP, not including delegators /// 2) % Cut of delegator tokens taken during reward /// 3) Bool indicating whether this SP has met min/max requirements /// 4) Number of endpoints registered by SP /// 5) Minimum deployer stake for this service provider /// 6) Maximum total stake for this account struct ServiceProviderDetails { uint256 deployerStake; uint256 deployerCut; bool validBounds; uint256 numberOfEndpoints; uint256 minAccountStake; uint256 maxAccountStake; } /// @dev - Data structure for time delay during withdrawal struct DecreaseStakeRequest { uint256 decreaseAmount; uint256 lockupExpiryBlock; } /// @dev - Data structure for time delay during deployer cut update struct UpdateDeployerCutRequest { uint256 newDeployerCut; uint256 lockupExpiryBlock; } /// @dev - Struct maintaining information about sp /// @dev - blocknumber is block.number when endpoint registered struct ServiceEndpoint { address owner; string endpoint; uint256 blocknumber; address delegateOwnerWallet; } /// @dev - Mapping of service provider address to details mapping(address => ServiceProviderDetails) private spDetails; /// @dev - Uniquely assigned serviceProvider ID, incremented for each service type /// @notice - Keeps track of the total number of services registered regardless of /// whether some have been deregistered since mapping(bytes32 => uint256) private serviceProviderTypeIDs; /// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo)) /// @notice - stores the actual service provider data like endpoint and owner wallet /// with the ability lookup by service type and service id */ mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo; /// @dev - mapping of keccak256(endpoint) to uint256 ID /// @notice - used to check if a endpoint has already been registered and also lookup /// the id of an endpoint mapping(bytes32 => uint256) private serviceProviderEndpointToId; /// @dev - mapping of address -> sp id array */ /// @notice - stores all the services registered by a provider. for each address, /// provides the ability to lookup by service type and see all registered services mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId; /// @dev - Mapping of service provider -> decrease stake request mapping(address => DecreaseStakeRequest) private decreaseStakeRequests; /// @dev - Mapping of service provider -> update deployer cut requests mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests; event RegisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _stakeAmount ); event DeregisteredServiceProvider( uint256 indexed _spID, bytes32 indexed _serviceType, address indexed _owner, string _endpoint, uint256 _unstakeAmount ); event IncreasedStake( address indexed _owner, uint256 indexed _increaseAmount, uint256 indexed _newStakeAmount ); event DecreaseStakeRequested( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _lockupExpiryBlock ); event DecreaseStakeRequestCancelled( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _lockupExpiryBlock ); event DecreaseStakeRequestEvaluated( address indexed _owner, uint256 indexed _decreaseAmount, uint256 indexed _newStakeAmount ); event EndpointUpdated( bytes32 indexed _serviceType, address indexed _owner, string _oldEndpoint, string _newEndpoint, uint256 indexed _spID ); event DelegateOwnerWalletUpdated( address indexed _owner, bytes32 indexed _serviceType, uint256 indexed _spID, address _updatedWallet ); event DeployerCutUpdateRequested( address indexed _owner, uint256 indexed _updatedCut, uint256 indexed _lockupExpiryBlock ); event DeployerCutUpdateRequestCancelled( address indexed _owner, uint256 indexed _requestedCut, uint256 indexed _finalCut ); event DeployerCutUpdateRequestEvaluated( address indexed _owner, uint256 indexed _updatedCut ); event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration); event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress); event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed * @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _governanceAddress - Governance proxy address */ function initialize ( address _governanceAddress, address _claimsManagerAddress, uint256 _decreaseStakeLockupDuration, uint256 _deployerCutLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); claimsManagerAddress = _claimsManagerAddress; _updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration); _updateDeployerCutLockupDuration(_deployerCutLockupDuration); InitializableV2.initialize(); } /** * @notice Register a new endpoint to the account of msg.sender * @dev Transfers stake from service provider into staking pool * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager * @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties * @return New service provider ID for this endpoint */ function register( bytes32 _serviceType, string calldata _endpoint, uint256 _stakeAmount, address _delegateOwnerWallet ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType), "ServiceProviderFactory: Valid service type required"); // Stake token amount from msg.sender if (_stakeAmount > 0) { require( !_claimPending(msg.sender), "ServiceProviderFactory: No pending claim expected" ); Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount); } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0, "ServiceProviderFactory: Endpoint already registered"); uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1); serviceProviderTypeIDs[_serviceType] = newServiceProviderID; // Index spInfo serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({ owner: msg.sender, endpoint: _endpoint, blocknumber: block.number, delegateOwnerWallet: _delegateOwnerWallet }); // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID; // Update (address -> type -> ids[]) serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID); // Increment number of endpoints for this address spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_stakeAmount) ); // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit RegisteredServiceProvider( newServiceProviderID, _serviceType, msg.sender, _endpoint, currentlyStakedForOwner ); return newServiceProviderID; } /** * @notice Deregister an endpoint from the account of msg.sender * @dev Unstakes all tokens for service provider if this is the last endpoint * @param _serviceType - type of service to deregister * @param _endpoint - endpoint to deregister * @return spId of the service that was deregistered */ function deregister( bytes32 _serviceType, string calldata _endpoint ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceTypeManagerAddressIsSet(); // Unstake on deregistration if and only if this is the last service endpoint uint256 unstakeAmount = 0; bool unstaked = false; // owned by the service provider if (spDetails[msg.sender].numberOfEndpoints == 1) { unstakeAmount = spDetails[msg.sender].deployerStake; // Submit request to decrease stake, overriding any pending request decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: unstakeAmount, lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration) }); unstaked = true; } require ( serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0, "ServiceProviderFactory: Endpoint not registered"); // Cache invalided service provider ID uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; // Update endpoint mapping serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0; require( keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)), "ServiceProviderFactory: Invalid endpoint for service type"); require ( serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender, "ServiceProviderFactory: Only callable by endpoint owner"); // Update info mapping delete serviceProviderInfo[_serviceType][deregisteredID]; // Reset id, update array uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length; for (uint256 i = 0; i < spTypeLength; i ++) { if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) { // Overwrite element to be deleted with last element in array serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1]; // Reduce array size, exit loop serviceProviderAddressToId[msg.sender][_serviceType].length--; // Confirm this ID has been found for the service provider break; } } // Decrement number of endpoints for this address spDetails[msg.sender].numberOfEndpoints -= 1; // Update min and max totals for this service provider (, uint256 typeMin, uint256 typeMax) = ServiceTypeManager( serviceTypeManagerAddress ).getServiceTypeInfo(_serviceType); spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin); spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax); emit DeregisteredServiceProvider( deregisteredID, _serviceType, msg.sender, _endpoint, unstakeAmount); // Confirm both aggregate account balance and directly staked amount are valid // Only if unstake operation has not occurred if (!unstaked) { this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; } return deregisteredID; } /** * @notice Increase stake for service provider * @param _increaseStakeAmount - amount to increase staked amount by * @return New total stake for service provider */ function increaseStake( uint256 _increaseStakeAmount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); // Confirm owner has an endpoint require( spDetails[msg.sender].numberOfEndpoints > 0, "ServiceProviderFactory: Registered endpoint required to increase stake" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); // Stake increased token amount for msg.sender stakingContract.stakeFor(msg.sender, _increaseStakeAmount); uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.add(_increaseStakeAmount) ); // Confirm both aggregate account balance and directly staked amount are valid this.validateAccountStakeBalance(msg.sender); // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; emit IncreasedStake( msg.sender, _increaseStakeAmount, newStakeAmount ); return newStakeAmount; } /** * @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after which the actual decreaseStake can be called * @dev Decreasing stake is only processed if a service provider is within valid bounds * @param _decreaseStakeAmount - amount to decrease stake by in wei * @return New total stake amount after the lockup */ function requestDecreaseStake(uint256 _decreaseStakeAmount) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( _decreaseStakeAmount > 0, "ServiceProviderFactory: Requested stake decrease amount must be greater than zero" ); require( !_claimPending(msg.sender), "ServiceProviderFactory: No claim expected to be pending prior to stake transfer" ); Staking stakingContract = Staking( stakingAddress ); uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender); // Prohibit decreasing stake to invalid bounds _validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount))); uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration); decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({ decreaseAmount: _decreaseStakeAmount, lockupExpiryBlock: expiryBlock }); emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock); return currentStakeAmount.sub(_decreaseStakeAmount); } /** * @notice Cancel a decrease stake request during the lockup * @dev Either called by the service provider via DelegateManager or governance during a slash action * @param _account - address of service provider */ function cancelDecreaseStakeRequest(address _account) external { _requireIsInitialized(); _requireDelegateManagerAddressIsSet(); require( msg.sender == _account || msg.sender == delegateManagerAddress, "ServiceProviderFactory: Only owner or DelegateManager" ); require( _decreaseRequestIsPending(_account), "ServiceProviderFactory: Decrease stake request must be pending" ); DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account]; // Clear decrease stake request decreaseStakeRequests[_account] = DecreaseStakeRequest({ decreaseAmount: 0, lockupExpiryBlock: 0 }); emit DecreaseStakeRequestCancelled( _account, cancelledRequest.decreaseAmount, cancelledRequest.lockupExpiryBlock ); } /** * @notice Called by user to decrease a stake after waiting the appropriate lockup period. * @return New total stake after decrease */ function decreaseStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); require( _decreaseRequestIsPending(msg.sender), "ServiceProviderFactory: Decrease stake request must be pending" ); require( decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); Staking stakingContract = Staking( stakingAddress ); uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount; // Decrease staked token amount for msg.sender stakingContract.unstakeFor(msg.sender, decreaseAmount); // Query current stake uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender); // Update deployer total spDetails[msg.sender].deployerStake = ( spDetails[msg.sender].deployerStake.sub(decreaseAmount) ); // Confirm both aggregate account balance and directly staked amount are valid // During registration this validation is bypassed since no endpoints remain if (spDetails[msg.sender].numberOfEndpoints > 0) { this.validateAccountStakeBalance(msg.sender); } // Indicate this service provider is within bounds spDetails[msg.sender].validBounds = true; // Clear decrease stake request delete decreaseStakeRequests[msg.sender]; emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount); return newStakeAmount; } /** * @notice Update delegate owner wallet for a given endpoint * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _endpoint - url of the service to register - url of the service to register * @param _updatedDelegateOwnerWallet - address of new delegate wallet */ function updateDelegateOwnerWallet( bytes32 _serviceType, string calldata _endpoint, address _updatedDelegateOwnerWallet ) external { _requireIsInitialized(); uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint); require( serviceProviderInfo[_serviceType][spID].owner == msg.sender, "ServiceProviderFactory: Invalid update operation, wrong owner" ); serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet; emit DelegateOwnerWalletUpdated( msg.sender, _serviceType, spID, _updatedDelegateOwnerWallet ); } /** * @notice Update the endpoint for a given service * @param _serviceType - type of service to register, must be valid in ServiceTypeManager * @param _oldEndpoint - old endpoint currently registered * @param _newEndpoint - new endpoint to replace old endpoint * @return ID of updated service provider */ function updateEndpoint( bytes32 _serviceType, string calldata _oldEndpoint, string calldata _newEndpoint ) external returns (uint256) { _requireIsInitialized(); uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint); require ( spId != 0, "ServiceProviderFactory: Could not find service provider with that endpoint" ); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId]; require( serviceEndpoint.owner == msg.sender, "ServiceProviderFactory: Invalid update endpoint operation, wrong owner" ); require( keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)), "ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider" ); // invalidate old endpoint serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0; // update to new endpoint serviceEndpoint.endpoint = _newEndpoint; serviceProviderInfo[_serviceType][spId] = serviceEndpoint; serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId; emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId); return spId; } /** * @notice Update the deployer cut for a given service provider * @param _serviceProvider - address of service provider * @param _cut - new value for deployer cut */ function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) && (updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0), "ServiceProviderFactory: Update deployer cut operation pending" ); require( _cut <= DEPLOYER_CUT_BASE, "ServiceProviderFactory: Service Provider cut cannot exceed base value" ); uint256 expiryBlock = block.number + deployerCutLockupDuration; updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({ lockupExpiryBlock: expiryBlock, newDeployerCut: _cut }); emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock); } /** * @notice Cancel a pending request to update deployer cut * @param _serviceProvider - address of service provider */ function cancelUpdateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); UpdateDeployerCutRequest memory cancelledRequest = ( updateDeployerCutRequests[_serviceProvider] ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; emit DeployerCutUpdateRequestCancelled( _serviceProvider, cancelledRequest.newDeployerCut, spDetails[_serviceProvider].deployerCut ); } /** * @notice Evalue request to update service provider cut of claims * @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase. * @dev SPs will interact with this value as a percent, value translation done client side @dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round. */ function updateDeployerCut(address _serviceProvider) external { _requireIsInitialized(); _requirePendingDeployerCutOperation(_serviceProvider); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number, "ServiceProviderFactory: Lockup must be expired" ); spDetails[_serviceProvider].deployerCut = ( updateDeployerCutRequests[_serviceProvider].newDeployerCut ); // Zero out request information delete updateDeployerCutRequests[_serviceProvider]; emit DeployerCutUpdateRequestEvaluated( _serviceProvider, spDetails[_serviceProvider].deployerCut ); } /** * @notice Update service provider balance * @dev Called by DelegateManager by functions modifying entire stake like claim and slash * @param _serviceProvider - address of service provider * @param _amount - new amount of direct state for service provider */ function updateServiceProviderStake( address _serviceProvider, uint256 _amount ) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireDelegateManagerAddressIsSet(); require( msg.sender == delegateManagerAddress, "ServiceProviderFactory: only callable by DelegateManager" ); // Update SP tracked total spDetails[_serviceProvider].deployerStake = _amount; _updateServiceProviderBoundStatus(_serviceProvider); } /// @notice Update service provider lockup duration function updateDecreaseStakeLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDecreaseStakeLockupDuration(_duration); emit DecreaseStakeLockupDurationUpdated(_duration); } /// @notice Update service provider lockup duration function updateDeployerCutLockupDuration(uint256 _duration) external { _requireIsInitialized(); require( msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE ); _updateDeployerCutLockupDuration(_duration); emit UpdateDeployerCutLockupDurationUpdated(_duration); } /// @notice Get denominator for deployer cut calculations function getServiceProviderDeployerCutBase() external view returns (uint256) { _requireIsInitialized(); return DEPLOYER_CUT_BASE; } /// @notice Get current deployer cut update lockup duration function getDeployerCutLockupDuration() external view returns (uint256) { _requireIsInitialized(); return deployerCutLockupDuration; } /// @notice Get total number of service providers for a given serviceType function getTotalServiceTypeProviders(bytes32 _serviceType) external view returns (uint256) { _requireIsInitialized(); return serviceProviderTypeIDs[_serviceType]; } /// @notice Get service provider id for an endpoint function getServiceProviderIdFromEndpoint(string calldata _endpoint) external view returns (uint256) { _requireIsInitialized(); return serviceProviderEndpointToId[keccak256(bytes(_endpoint))]; } /** * @notice Get service provider ids for a given service provider and service type * @return List of service ids of that type for a service provider */ function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType) external view returns (uint256[] memory) { _requireIsInitialized(); return serviceProviderAddressToId[_ownerAddress][_serviceType]; } /** * @notice Get information about a service endpoint given its service id * @param _serviceType - type of service, must be a valid service from ServiceTypeManager * @param _serviceId - id of service */ function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId) external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet) { _requireIsInitialized(); ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId]; return ( serviceEndpoint.owner, serviceEndpoint.endpoint, serviceEndpoint.blocknumber, serviceEndpoint.delegateOwnerWallet ); } /** * @notice Get information about a service provider given their address * @param _serviceProvider - address of service provider */ function getServiceProviderDetails(address _serviceProvider) external view returns ( uint256 deployerStake, uint256 deployerCut, bool validBounds, uint256 numberOfEndpoints, uint256 minAccountStake, uint256 maxAccountStake) { _requireIsInitialized(); return ( spDetails[_serviceProvider].deployerStake, spDetails[_serviceProvider].deployerCut, spDetails[_serviceProvider].validBounds, spDetails[_serviceProvider].numberOfEndpoints, spDetails[_serviceProvider].minAccountStake, spDetails[_serviceProvider].maxAccountStake ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingDecreaseStakeRequest(address _serviceProvider) external view returns (uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( decreaseStakeRequests[_serviceProvider].decreaseAmount, decreaseStakeRequests[_serviceProvider].lockupExpiryBlock ); } /** * @notice Get information about pending decrease stake requests for service provider * @param _serviceProvider - address of service provider */ function getPendingUpdateDeployerCutRequest(address _serviceProvider) external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock) { _requireIsInitialized(); return ( updateDeployerCutRequests[_serviceProvider].newDeployerCut, updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock ); } /// @notice Get current unstake lockup duration function getDecreaseStakeLockupDuration() external view returns (uint256) { _requireIsInitialized(); return decreaseStakeLockupDuration; } /** * @notice Validate that the total service provider balance is between the min and max stakes for all their registered services and validate direct stake for sp is above minimum * @param _serviceProvider - address of service provider */ function validateAccountStakeBalance(address _serviceProvider) external view { _requireIsInitialized(); _requireStakingAddressIsSet(); _validateBalanceInternal( _serviceProvider, Staking(stakingAddress).totalStakedFor(_serviceProvider) ); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /// @notice Get the ServiceTypeManager address function getServiceTypeManagerAddress() external view returns (address) { _requireIsInitialized(); return serviceTypeManagerAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _address - address for new Staking contract */ function setStakingAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _address; emit StakingAddressUpdated(_address); } /** * @notice Set the DelegateManager address * @dev Only callable by Governance address * @param _address - address for new DelegateManager contract */ function setDelegateManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); delegateManagerAddress = _address; emit DelegateManagerAddressUpdated(_address); } /** * @notice Set the ServiceTypeManager address * @dev Only callable by Governance address * @param _address - address for new ServiceTypeManager contract */ function setServiceTypeManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceTypeManagerAddress = _address; emit ServiceTypeManagerAddressUpdated(_address); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _address - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _address) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _address; emit ClaimsManagerAddressUpdated(_address); } // ========================================= Internal Functions ========================================= /** * @notice Update status in spDetails if the bounds for a service provider is valid */ function _updateServiceProviderBoundStatus(address _serviceProvider) internal { // Validate bounds for total stake uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider); if (totalSPStake < spDetails[_serviceProvider].minAccountStake || totalSPStake > spDetails[_serviceProvider].maxAccountStake) { // Indicate this service provider is out of bounds spDetails[_serviceProvider].validBounds = false; } else { // Indicate this service provider is within bounds spDetails[_serviceProvider].validBounds = true; } } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "ServiceProviderFactory: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the deployer cut lockup duration * @param _duration - incoming duration */ function _updateDeployerCutLockupDuration(uint256 _duration) internal { require( ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration, "ServiceProviderFactory: Incoming duration must be greater than funding round block diff" ); deployerCutLockupDuration = _duration; } /** * @notice Set the decrease stake lockup duration * @param _duration - incoming duration */ function _updateDecreaseStakeLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); decreaseStakeLockupDuration = _duration; } /** * @notice Compare a given amount input against valid min and max bounds for service provider * @param _serviceProvider - address of service provider * @param _amount - amount in wei to compare */ function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view { require( _amount <= spDetails[_serviceProvider].maxAccountStake, "ServiceProviderFactory: Maximum stake amount exceeded" ); require( spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake, "ServiceProviderFactory: Minimum stake requirement not met" ); } /** * @notice Get whether a decrease request has been initiated for service provider * @param _serviceProvider - address of service provider * return Boolean of whether decrease request has been initiated */ function _decreaseRequestIsPending(address _serviceProvider) internal view returns (bool) { return ( (decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) && (decreaseStakeRequests[_serviceProvider].decreaseAmount > 0) ); } /** * @notice Boolean indicating whether a claim is pending for this service provider */ /** * @notice Get whether a claim is pending for this service provider * @param _serviceProvider - address of service provider * return Boolean of whether claim is pending */ function _claimPending(address _serviceProvider) internal view returns (bool) { return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider); } // ========================================= Private Functions ========================================= function _requirePendingDeployerCutOperation (address _serviceProvider) private view { require( (updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0), "ServiceProviderFactory: No update deployer cut operation pending" ); } function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "ServiceProviderFactory: stakingAddress is not set" ); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "ServiceProviderFactory: delegateManagerAddress is not set" ); } function _requireServiceTypeManagerAddressIsSet() private view { require( serviceTypeManagerAddress != address(0x00), "ServiceProviderFactory: serviceTypeManagerAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "ServiceProviderFactory: claimsManagerAddress is not set" ); } } /// @notice SafeMath imported via ServiceProviderFactory.sol /// @notice Governance imported via Staking.sol /** * Designed to manage delegation to staking contract */ contract DelegateManager is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "DelegateManager: Only callable by Governance contract" ); string private constant ERROR_MINIMUM_DELEGATION = ( "DelegateManager: Minimum delegation amount required" ); string private constant ERROR_ONLY_SP_GOVERNANCE = ( "DelegateManager: Only callable by target SP or governance" ); string private constant ERROR_DELEGATOR_STAKE = ( "DelegateManager: Delegator must be staked for SP" ); address private governanceAddress; address private stakingAddress; address private serviceProviderFactoryAddress; address private claimsManagerAddress; /** * Period in blocks an undelegate operation is delayed. * The undelegate operation speed bump is to prevent a delegator from * attempting to remove their delegation in anticipation of a slash. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private undelegateLockupDuration; /// @notice Maximum number of delegators a single account can handle uint256 private maxDelegators; /// @notice Minimum amount of delegation allowed uint256 private minDelegationAmount; /** * Lockup duration for a remove delegator request. * The remove delegator speed bump is to prevent a service provider from maliciously * removing a delegator prior to the evaluation of a proposal. * @notice Must be greater than governance votingPeriod + executionDelay */ uint256 private removeDelegatorLockupDuration; /** * Evaluation period for a remove delegator request * @notice added to expiry block calculated for removeDelegatorLockupDuration */ uint256 private removeDelegatorEvalDuration; // Staking contract ref ERC20Mintable private audiusToken; // Struct representing total delegated to SP and list of delegators struct ServiceProviderDelegateInfo { uint256 totalDelegatedStake; uint256 totalLockedUpStake; address[] delegators; } // Data structures for lockup during withdrawal struct UndelegateStakeRequest { address serviceProvider; uint256 amount; uint256 lockupExpiryBlock; } // Service provider address -> ServiceProviderDelegateInfo mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo; // Delegator stake by address delegated to // delegator -> (service provider -> delegatedStake) mapping (address => mapping(address => uint256)) private delegateInfo; // Delegator stake total by address // delegator -> (totalDelegated) // Note - delegator properties are maintained in a mapping instead of struct // in order to facilitate extensibility in the future. mapping (address => uint256) private delegatorTotalStake; // Requester to pending undelegate request mapping (address => UndelegateStakeRequest) private undelegateRequests; // Pending remove delegator requests // service provider -> (delegator -> lockupExpiryBlock) mapping (address => mapping (address => uint256)) private removeDelegatorRequests; event IncreaseDelegatedStake( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _increaseAmount ); event UndelegateStakeRequested( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount, uint256 _lockupExpiryBlock ); event UndelegateStakeRequestCancelled( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event UndelegateStakeRequestEvaluated( address indexed _delegator, address indexed _serviceProvider, uint256 indexed _amount ); event Claim( address indexed _claimer, uint256 indexed _rewards, uint256 indexed _newTotal ); event Slash( address indexed _target, uint256 indexed _amount, uint256 indexed _newTotal ); event RemoveDelegatorRequested( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _lockupExpiryBlock ); event RemoveDelegatorRequestCancelled( address indexed _serviceProvider, address indexed _delegator ); event RemoveDelegatorRequestEvaluated( address indexed _serviceProvider, address indexed _delegator, uint256 indexed _unstakedAmount ); event MaxDelegatorsUpdated(uint256 indexed _maxDelegators); event MinDelegationUpdated(uint256 indexed _minDelegationAmount); event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration); event GovernanceAddressUpdated(address indexed _newGovernanceAddress); event StakingAddressUpdated(address indexed _newStakingAddress); event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress); event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress); event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration); event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration); /** * @notice Function to initialize the contract * @dev stakingAddress must be initialized separately after Staking contract is deployed * @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed * @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed * @param _tokenAddress - address of ERC20 token that will be claimed * @param _governanceAddress - Governance proxy address */ function initialize ( address _tokenAddress, address _governanceAddress, uint256 _undelegateLockupDuration ) public initializer { _updateGovernanceAddress(_governanceAddress); audiusToken = ERC20Mintable(_tokenAddress); maxDelegators = 175; // Default minimum delegation amount set to 100AUD minDelegationAmount = 100 * 10**uint256(18); InitializableV2.initialize(); _updateUndelegateLockupDuration(_undelegateLockupDuration); // 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks _updateRemoveDelegatorLockupDuration(46523); // 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks removeDelegatorEvalDuration = 6646; } /** * @notice Allow a delegator to delegate stake to a service provider * @param _targetSP - address of service provider to delegate to * @param _amount - amount in wei to delegate * @return Updated total amount delegated to the service provider by delegator */ function delegateStake( address _targetSP, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); require( !_claimPending(_targetSP), "DelegateManager: Delegation not permitted for SP pending claim" ); address delegator = msg.sender; Staking stakingContract = Staking(stakingAddress); // Stake on behalf of target service provider stakingContract.delegateStakeFor( _targetSP, delegator, _amount ); // Update list of delegators to SP if necessary if (!_delegatorExistsForSP(delegator, _targetSP)) { // If not found, update list of delegates spDelegateInfo[_targetSP].delegators.push(delegator); require( spDelegateInfo[_targetSP].delegators.length <= maxDelegators, "DelegateManager: Maximum delegators exceeded" ); } // Update following values in storage through helper // totalServiceProviderDelegatedStake = current sp total + new amount, // totalStakedForSpFromDelegator = current delegator total for sp + new amount, // totalDelegatorStake = current delegator total + new amount _updateDelegatorStake( delegator, _targetSP, spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount), delegateInfo[delegator][_targetSP].add(_amount), delegatorTotalStake[delegator].add(_amount) ); require( delegateInfo[delegator][_targetSP] >= minDelegationAmount, ERROR_MINIMUM_DELEGATION ); // Validate balance ServiceProviderFactory( serviceProviderFactoryAddress ).validateAccountStakeBalance(_targetSP); emit IncreaseDelegatedStake( delegator, _targetSP, _amount ); // Return new total return delegateInfo[delegator][_targetSP]; } /** * @notice Submit request for undelegation * @param _target - address of service provider to undelegate stake from * @param _amount - amount in wei to undelegate * @return Updated total amount delegated to the service provider by delegator */ function requestUndelegateStake( address _target, uint256 _amount ) external returns (uint256) { _requireIsInitialized(); _requireClaimsManagerAddressIsSet(); require( _amount > 0, "DelegateManager: Requested undelegate stake amount must be greater than zero" ); require( !_claimPending(_target), "DelegateManager: Undelegate request not permitted for SP pending claim" ); address delegator = msg.sender; require( _delegatorExistsForSP(delegator, _target), ERROR_DELEGATOR_STAKE ); // Confirm no pending delegation request require( !_undelegateRequestIsPending(delegator), "DelegateManager: No pending lockup expected" ); // Ensure valid bounds uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target]; require( _amount <= currentlyDelegatedToSP, "DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider" ); // Submit updated request for sender, with target sp, undelegate amount, target expiry block uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration); _updateUndelegateStakeRequest( delegator, _target, _amount, lockupExpiryBlock ); // Update total locked for this service provider, increasing by unstake amount _updateServiceProviderLockupAmount( _target, spDelegateInfo[_target].totalLockedUpStake.add(_amount) ); emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock); return delegateInfo[delegator][_target].sub(_amount); } /** * @notice Cancel undelegation request */ function cancelUndelegateStakeRequest() external { _requireIsInitialized(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); uint256 unstakeAmount = undelegateRequests[delegator].amount; address unlockFundsSP = undelegateRequests[delegator].serviceProvider; // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( unlockFundsSP, spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount) ); // Remove pending request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount); } /** * @notice Finalize undelegation request and withdraw stake * @return New total amount currently staked after stake has been undelegated */ function undelegateStake() external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); address delegator = msg.sender; // Confirm pending delegation request require( _undelegateRequestIsPending(delegator), "DelegateManager: Pending lockup expected" ); // Confirm lockup expiry has expired require( undelegateRequests[delegator].lockupExpiryBlock <= block.number, "DelegateManager: Lockup must be expired" ); // Confirm no pending claim for this service provider require( !_claimPending(undelegateRequests[delegator].serviceProvider), "DelegateManager: Undelegate not permitted for SP pending claim" ); address serviceProvider = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( serviceProvider, delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( delegator, serviceProvider, spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[delegator][serviceProvider].sub(unstakeAmount), delegatorTotalStake[delegator].sub(unstakeAmount) ); require( (delegateInfo[delegator][serviceProvider] >= minDelegationAmount || delegateInfo[delegator][serviceProvider] == 0), ERROR_MINIMUM_DELEGATION ); // Remove from delegators list if no delegated stake remaining if (delegateInfo[delegator][serviceProvider] == 0) { _removeFromDelegatorsList(serviceProvider, delegator); } // Update total locked for this service provider, decreasing by unstake amount _updateServiceProviderLockupAmount( serviceProvider, spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount) ); // Reset undelegate request _resetUndelegateStakeRequest(delegator); emit UndelegateStakeRequestEvaluated( delegator, serviceProvider, unstakeAmount ); // Return new total return delegateInfo[delegator][serviceProvider]; } /** * @notice Claim and distribute rewards to delegators and service provider as necessary * @param _serviceProvider - Provider for which rewards are being distributed * @dev Factors in service provider rewards from delegator and transfers deployer cut */ function claimRewards(address _serviceProvider) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireClaimsManagerAddressIsSet(); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager)) ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) = _validateClaimRewards(spFactory, _serviceProvider); // No-op if balance is already equivalent // This case can occur if no rewards due to bound violation or all stake is locked if (totalRewards == 0) { return; } uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards( _serviceProvider, totalActiveFunds, totalRewards, deployerCut, spFactory.getServiceProviderDeployerCutBase() ); // Update total delegated to this SP spDelegateInfo[_serviceProvider].totalDelegatedStake = ( spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease) ); // spRewardShare represents rewards directly allocated to service provider for their stake // Value is computed as the remainder of total minted rewards after distribution to // delegators, eliminating any potential for precision loss. uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease); // Adding the newly calculated reward share to current balance uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare); require( totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake), "DelegateManager: claimRewards amount mismatch" ); spFactory.updateServiceProviderStake( _serviceProvider, newSPFactoryBalance ); } /** * @notice Reduce current stake amount * @dev Only callable by governance. Slashes service provider and delegators equally * @param _amount - amount in wei to slash * @param _slashAddress - address of service provider to slash */ function slash(uint256 _amount, address _slashAddress) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); Staking stakingContract = Staking(stakingAddress); ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); // Amount stored in staking contract for owner uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress); require( (totalBalanceInStakingPreSlash >= _amount), "DelegateManager: Cannot slash more than total currently staked" ); // Cancel any withdrawal request for this service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress); if (spLockedStake > 0) { spFactory.cancelDecreaseStakeRequest(_slashAddress); } // Amount in sp factory for slash target (uint256 totalBalanceInSPFactory,,,,,) = ( spFactory.getServiceProviderDetails(_slashAddress) ); require( totalBalanceInSPFactory > 0, "DelegateManager: Service Provider stake required" ); // Decrease value in Staking contract // A value of zero slash will fail in staking, reverting this transaction stakingContract.slash(_amount, _slashAddress); uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress); // Emit slash event emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash); uint256 totalDelegatedStakeDecrease = 0; // For each delegator and deployer, recalculate new value // newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash) for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) { address delegator = spDelegateInfo[_slashAddress].delegators[i]; uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress]; uint256 newDelegateStake = ( totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake) ).div(totalBalanceInStakingPreSlash); // slashAmountForDelegator = preSlashDelegateStake - newDelegateStake; delegateInfo[delegator][_slashAddress] = ( delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total stake for delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake)) ); // Update total decrease amount totalDelegatedStakeDecrease = ( totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake)) ); // Check for any locked up funds for this slashed delegator // Slash overrides any pending withdrawal requests if (undelegateRequests[delegator].amount != 0) { address unstakeSP = undelegateRequests[delegator].serviceProvider; uint256 unstakeAmount = undelegateRequests[delegator].amount; // Remove pending request _updateServiceProviderLockupAmount( unstakeSP, spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount) ); _resetUndelegateStakeRequest(delegator); } } // Update total delegated to this SP spDelegateInfo[_slashAddress].totalDelegatedStake = ( spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease) ); // Remaining decrease applied to service provider uint256 totalStakeDecrease = ( totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash) ); uint256 totalSPFactoryBalanceDecrease = ( totalStakeDecrease.sub(totalDelegatedStakeDecrease) ); spFactory.updateServiceProviderStake( _slashAddress, totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease) ); } /** * @notice Initiate forcible removal of a delegator * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function requestRemoveDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] == 0, "DelegateManager: Pending remove delegator request" ); require( _delegatorExistsForSP(_delegator, _serviceProvider), ERROR_DELEGATOR_STAKE ); // Update lockup removeDelegatorRequests[_serviceProvider][_delegator] = ( block.number + removeDelegatorLockupDuration ); emit RemoveDelegatorRequested( _serviceProvider, _delegator, removeDelegatorRequests[_serviceProvider][_delegator] ); } /** * @notice Cancel pending removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator */ function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external { require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator); } /** * @notice Evaluate removeDelegator request * @param _serviceProvider - address of service provider * @param _delegator - address of delegator * @return Updated total amount delegated to the service provider by delegator */ function removeDelegator(address _serviceProvider, address _delegator) external { _requireIsInitialized(); _requireStakingAddressIsSet(); require( msg.sender == _serviceProvider || msg.sender == governanceAddress, ERROR_ONLY_SP_GOVERNANCE ); require( removeDelegatorRequests[_serviceProvider][_delegator] != 0, "DelegateManager: No pending request" ); // Enforce lockup expiry block require( block.number >= removeDelegatorRequests[_serviceProvider][_delegator], "DelegateManager: Lockup must be expired" ); // Enforce evaluation window for request require( block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration, "DelegateManager: RemoveDelegator evaluation window expired" ); uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider]; // Unstake on behalf of target service provider Staking(stakingAddress).undelegateStakeFor( _serviceProvider, _delegator, unstakeAmount ); // Update total delegated for SP // totalServiceProviderDelegatedStake - total amount delegated to service provider // totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider _updateDelegatorStake( _delegator, _serviceProvider, spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount), delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount), delegatorTotalStake[_delegator].sub(unstakeAmount) ); if ( _undelegateRequestIsPending(_delegator) && undelegateRequests[_delegator].serviceProvider == _serviceProvider ) { // Remove pending request information _updateServiceProviderLockupAmount( _serviceProvider, spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount) ); _resetUndelegateStakeRequest(_delegator); } // Remove from list of delegators _removeFromDelegatorsList(_serviceProvider, _delegator); // Reset lockup expiry removeDelegatorRequests[_serviceProvider][_delegator] = 0; emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount); } /** * @notice Update duration for undelegate request lockup * @param _duration - new lockup duration */ function updateUndelegateLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateUndelegateLockupDuration(_duration); emit UndelegateLockupDurationUpdated(_duration); } /** * @notice Update maximum delegators allowed * @param _maxDelegators - new max delegators */ function updateMaxDelegators(uint256 _maxDelegators) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); maxDelegators = _maxDelegators; emit MaxDelegatorsUpdated(_maxDelegators); } /** * @notice Update minimum delegation amount * @param _minDelegationAmount - min new min delegation amount */ function updateMinDelegationAmount(uint256 _minDelegationAmount) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); minDelegationAmount = _minDelegationAmount; emit MinDelegationUpdated(_minDelegationAmount); } /** * @notice Update remove delegator lockup duration * @param _duration - new lockup duration */ function updateRemoveDelegatorLockupDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateRemoveDelegatorLockupDuration(_duration); emit RemoveDelegatorLockupDurationUpdated(_duration); } /** * @notice Update remove delegator evaluation window duration * @param _duration - new window duration */ function updateRemoveDelegatorEvalDuration(uint256 _duration) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); removeDelegatorEvalDuration = _duration; emit RemoveDelegatorEvalDurationUpdated(_duration); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); governanceAddress = _governanceAddress; emit GovernanceAddressUpdated(_governanceAddress); } /** * @notice Set the Staking address * @dev Only callable by Governance address * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); stakingAddress = _stakingAddress; emit StakingAddressUpdated(_stakingAddress); } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by Governance address * @param _spFactory - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _spFactory) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); serviceProviderFactoryAddress = _spFactory; emit ServiceProviderFactoryAddressUpdated(_spFactory); } /** * @notice Set the ClaimsManager address * @dev Only callable by Governance address * @param _claimsManagerAddress - address for new ClaimsManager contract */ function setClaimsManagerAddress(address _claimsManagerAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); claimsManagerAddress = _claimsManagerAddress; emit ClaimsManagerAddressUpdated(_claimsManagerAddress); } // ========================================= View Functions ========================================= /** * @notice Get list of delegators for a given service provider * @param _sp - service provider address */ function getDelegatorsList(address _sp) external view returns (address[] memory) { _requireIsInitialized(); return spDelegateInfo[_sp].delegators; } /** * @notice Get total delegation from a given address * @param _delegator - delegator address */ function getTotalDelegatorStake(address _delegator) external view returns (uint256) { _requireIsInitialized(); return delegatorTotalStake[_delegator]; } /// @notice Get total amount delegated to a service provider function getTotalDelegatedToServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalDelegatedStake; } /// @notice Get total delegated stake locked up for a service provider function getTotalLockedDelegationForServiceProvider(address _sp) external view returns (uint256) { _requireIsInitialized(); return spDelegateInfo[_sp].totalLockedUpStake; } /// @notice Get total currently staked for a delegator, for a given service provider function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider) external view returns (uint256) { _requireIsInitialized(); return delegateInfo[_delegator][_serviceProvider]; } /** * @notice Get status of pending undelegate request for a given address * @param _delegator - address of the delegator */ function getPendingUndelegateRequest(address _delegator) external view returns (address target, uint256 amount, uint256 lockupExpiryBlock) { _requireIsInitialized(); UndelegateStakeRequest memory req = undelegateRequests[_delegator]; return (req.serviceProvider, req.amount, req.lockupExpiryBlock); } /** * @notice Get status of pending remove delegator request for a given address * @param _serviceProvider - address of the service provider * @param _delegator - address of the delegator * @return - current lockup expiry block for remove delegator request */ function getPendingRemoveDelegatorRequest( address _serviceProvider, address _delegator ) external view returns (uint256) { _requireIsInitialized(); return removeDelegatorRequests[_serviceProvider][_delegator]; } /// @notice Get current undelegate lockup duration function getUndelegateLockupDuration() external view returns (uint256) { _requireIsInitialized(); return undelegateLockupDuration; } /// @notice Current maximum delegators function getMaxDelegators() external view returns (uint256) { _requireIsInitialized(); return maxDelegators; } /// @notice Get minimum delegation amount function getMinDelegationAmount() external view returns (uint256) { _requireIsInitialized(); return minDelegationAmount; } /// @notice Get the duration for remove delegator request lockup function getRemoveDelegatorLockupDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorLockupDuration; } /// @notice Get the duration for evaluation of remove delegator operations function getRemoveDelegatorEvalDuration() external view returns (uint256) { _requireIsInitialized(); return removeDelegatorEvalDuration; } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the ClaimsManager address function getClaimsManagerAddress() external view returns (address) { _requireIsInitialized(); return claimsManagerAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } // ========================================= Internal functions ========================================= /** * @notice Helper function for claimRewards to get balances from Staking contract and do validation * @param spFactory - reference to ServiceProviderFactory contract * @param _serviceProvider - address for which rewards are being claimed * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut) */ function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider) internal returns ( uint256 totalBalanceInStaking, uint256 totalBalanceInSPFactory, uint256 totalActiveFunds, uint256 totalRewards, uint256 deployerCut ) { // Account for any pending locked up stake for the service provider (uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider); uint256 totalLockedUpStake = ( spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake) ); // Process claim for msg.sender // Total locked parameter is equal to delegate locked up stake + service provider locked up stake uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim( _serviceProvider, totalLockedUpStake ); // Amount stored in staking contract for owner totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider); // Amount in sp factory for claimer ( totalBalanceInSPFactory, deployerCut, ,,, ) = spFactory.getServiceProviderDetails(_serviceProvider); // Require active stake to claim any rewards // Amount in delegate manager staked to service provider uint256 totalBalanceOutsideStaking = ( totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake) ); totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake); require( mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking), "DelegateManager: Reward amount mismatch" ); // Emit claim event emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking); return ( totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, mintedRewards, deployerCut ); } /** * @notice Perform state updates when a delegate stake has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _totalServiceProviderDelegatedStake - total delegated to this service provider * @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator * @param _totalDelegatorStake - total delegated from this delegator address */ function _updateDelegatorStake( address _delegator, address _serviceProvider, uint256 _totalServiceProviderDelegatedStake, uint256 _totalStakedForSpFromDelegator, uint256 _totalDelegatorStake ) internal { // Update total delegated for SP spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake; // Update amount staked from this delegator to targeted service provider delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator; // Update total delegated from this delegator _updateDelegatorTotalStake(_delegator, _totalDelegatorStake); } /** * @notice Reset pending undelegate stake request * @param _delegator - address of delegator */ function _resetUndelegateStakeRequest(address _delegator) internal { _updateUndelegateStakeRequest(_delegator, address(0), 0, 0); } /** * @notice Perform updates when undelegate request state has changed * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @param _amount - amount being undelegated * @param _lockupExpiryBlock - block at which stake can be undelegated */ function _updateUndelegateStakeRequest( address _delegator, address _serviceProvider, uint256 _amount, uint256 _lockupExpiryBlock ) internal { // Update lockup information undelegateRequests[_delegator] = UndelegateStakeRequest({ lockupExpiryBlock: _lockupExpiryBlock, amount: _amount, serviceProvider: _serviceProvider }); } /** * @notice Update total amount delegated from an address * @param _delegator - address of service provider * @param _amount - updated delegator total */ function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal { delegatorTotalStake[_delegator] = _amount; } /** * @notice Update amount currently locked up for this service provider * @param _serviceProvider - address of service provider * @param _updatedLockupAmount - updated lock up amount */ function _updateServiceProviderLockupAmount( address _serviceProvider, uint256 _updatedLockupAmount ) internal { spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount; } function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { // Overwrite and shrink delegators list spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1]; spDelegateInfo[_serviceProvider].delegators.length--; break; } } } /** * @notice Helper function to distribute rewards to any delegators * @param _sp - service provider account tracked in staking * @param _totalActiveFunds - total funds minus any locked stake * @param _totalRewards - total rewaards generated in this round * @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase * @param _deployerCutBase - denominator value for calculating service provider cut as a % * @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking) */ function _distributeDelegateRewards( address _sp, uint256 _totalActiveFunds, uint256 _totalRewards, uint256 _deployerCut, uint256 _deployerCutBase ) internal returns (uint256 totalDelegatedStakeIncrease) { // Traverse all delegates and calculate their rewards // As each delegate reward is calculated, increment SP cut reward accordingly for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) { address delegator = spDelegateInfo[_sp].delegators[i]; uint256 delegateStakeToSP = delegateInfo[delegator][_sp]; // Subtract any locked up stake if (undelegateRequests[delegator].serviceProvider == _sp) { delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount); } // Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards) uint256 rewardsPriorToSPCut = ( delegateStakeToSP.mul(_totalRewards) ).div(_totalActiveFunds); // Multiply by deployer cut fraction to calculate reward for SP // Operation constructed to perform all multiplication prior to division // uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase); // = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase); // = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds); uint256 spDeployerCut = ( (delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut) ).div( _totalActiveFunds.mul(_deployerCutBase) ); // Increase total delegate reward in DelegateManager // Subtract SP reward from rewards to calculate delegate reward // delegateReward = rewardsPriorToSPCut - spDeployerCut; delegateInfo[delegator][_sp] = ( delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); // Update total for this delegator _updateDelegatorTotalStake( delegator, delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut)) ); totalDelegatedStakeIncrease = ( totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut)) ); } return (totalDelegatedStakeIncrease); } /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "DelegateManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } /** * @notice Set the remove delegator lockup duration after validating against governance * @param _duration - Incoming remove delegator duration value */ function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); removeDelegatorLockupDuration = _duration; } /** * @notice Set the undelegate lockup duration after validating against governance * @param _duration - Incoming undelegate lockup duration value */ function _updateUndelegateLockupDuration(uint256 _duration) internal { Governance governance = Governance(governanceAddress); require( _duration > governance.getVotingPeriod() + governance.getExecutionDelay(), "DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay" ); undelegateLockupDuration = _duration; } /** * @notice Returns if delegator has delegated to a service provider * @param _delegator - address of delegator * @param _serviceProvider - address of service provider * @return boolean indicating whether delegator exists for service provider */ function _delegatorExistsForSP( address _delegator, address _serviceProvider ) internal view returns (bool) { for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) { if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) { return true; } } // Not found return false; } /** * @notice Determine if a claim is pending for this service provider * @param _sp - address of service provider * @return boolean indicating whether a claim is pending */ function _claimPending(address _sp) internal view returns (bool) { ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress); return claimsManager.claimPending(_sp); } /** * @notice Determine if a decrease request has been initiated * @param _delegator - address of delegator * @return boolean indicating whether a decrease request is pending */ function _undelegateRequestIsPending(address _delegator) internal view returns (bool) { return ( (undelegateRequests[_delegator].lockupExpiryBlock != 0) && (undelegateRequests[_delegator].amount != 0) && (undelegateRequests[_delegator].serviceProvider != address(0)) ); } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "DelegateManager: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "DelegateManager: serviceProviderFactoryAddress is not set" ); } function _requireClaimsManagerAddressIsSet() private view { require( claimsManagerAddress != address(0x00), "DelegateManager: claimsManagerAddress is not set" ); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _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; } uint256[50] private ______gap; } /** * @title Central hub for Audius protocol. It stores all contract addresses to facilitate * external access and enable version management. */ contract Registry is InitializableV2, Ownable { using SafeMath for uint256; /** * @dev addressStorage mapping allows efficient lookup of current contract version * addressStorageHistory maintains record of all contract versions */ mapping(bytes32 => address) private addressStorage; mapping(bytes32 => address[]) private addressStorageHistory; event ContractAdded( bytes32 indexed _name, address indexed _address ); event ContractRemoved( bytes32 indexed _name, address indexed _address ); event ContractUpgraded( bytes32 indexed _name, address indexed _oldAddress, address indexed _newAddress ); function initialize() public initializer { /// @notice Ownable.initialize(address _sender) sets contract owner to _sender. Ownable.initialize(msg.sender); InitializableV2.initialize(); } // ========================================= Setters ========================================= /** * @notice addContract registers contract name to address mapping under given registry key * @param _name - registry key that will be used for lookups * @param _address - address of contract */ function addContract(bytes32 _name, address _address) external onlyOwner { _requireIsInitialized(); require( addressStorage[_name] == address(0x00), "Registry: Contract already registered with given name." ); require( _address != address(0x00), "Registry: Cannot register zero address." ); setAddress(_name, _address); emit ContractAdded(_name, _address); } /** * @notice removes contract address registered under given registry key * @param _name - registry key for lookup */ function removeContract(bytes32 _name) external onlyOwner { _requireIsInitialized(); address contractAddress = addressStorage[_name]; require( contractAddress != address(0x00), "Registry: Cannot remove - no contract registered with given _name." ); setAddress(_name, address(0x00)); emit ContractRemoved(_name, contractAddress); } /** * @notice replaces contract address registered under given key with provided address * @param _name - registry key for lookup * @param _newAddress - new contract address to register under given key */ function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner { _requireIsInitialized(); address oldAddress = addressStorage[_name]; require( oldAddress != address(0x00), "Registry: Cannot upgrade - no contract registered with given _name." ); require( _newAddress != address(0x00), "Registry: Cannot upgrade - cannot register zero address." ); setAddress(_name, _newAddress); emit ContractUpgraded(_name, oldAddress, _newAddress); } // ========================================= Getters ========================================= /** * @notice returns contract address registered under given registry key * @param _name - registry key for lookup * @return contractAddr - address of contract registered under given registry key */ function getContract(bytes32 _name) external view returns (address contractAddr) { _requireIsInitialized(); return addressStorage[_name]; } /// @notice overloaded getContract to return explicit version of contract function getContract(bytes32 _name, uint256 _version) external view returns (address contractAddr) { _requireIsInitialized(); // array length for key implies version number require( _version <= addressStorageHistory[_name].length, "Registry: Index out of range _version." ); return addressStorageHistory[_name][_version.sub(1)]; } /** * @notice Returns the number of versions for a contract key * @param _name - registry key for lookup * @return number of contract versions */ function getContractVersionCount(bytes32 _name) external view returns (uint256) { _requireIsInitialized(); return addressStorageHistory[_name].length; } // ========================================= Private functions ========================================= /** * @param _key the key for the contract address * @param _value the contract address */ function setAddress(bytes32 _key, address _value) private { // main map for cheap lookup addressStorage[_key] = _value; // keep track of contract address history addressStorageHistory[_key].push(_value); } } contract Governance is InitializableV2 { using SafeMath for uint256; string private constant ERROR_ONLY_GOVERNANCE = ( "Governance: Only callable by self" ); string private constant ERROR_INVALID_VOTING_PERIOD = ( "Governance: Requires non-zero _votingPeriod" ); string private constant ERROR_INVALID_REGISTRY = ( "Governance: Requires non-zero _registryAddress" ); string private constant ERROR_INVALID_VOTING_QUORUM = ( "Governance: Requires _votingQuorumPercent between 1 & 100" ); /** * @notice Address and contract instance of Audius Registry. Used to ensure this contract * can only govern contracts that are registered in the Audius Registry. */ Registry private registry; /// @notice Address of Audius staking contract, used to permission Governance method calls address private stakingAddress; /// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls address private serviceProviderFactoryAddress; /// @notice Address of Audius DelegateManager contract, used to permission Governance method calls address private delegateManagerAddress; /// @notice Period in blocks for which a governance proposal is open for voting uint256 private votingPeriod; /// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed uint256 private executionDelay; /// @notice Required minimum percentage of total stake to have voted to consider a proposal valid /// Percentaged stored as a uint256 between 0 & 100 /// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block) uint256 private votingQuorumPercent; /// @notice Max number of InProgress proposals possible at once /// @dev uint16 gives max possible value of 65,535 uint16 private maxInProgressProposals; /** * @notice Address of account that has special Governance permissions. Can veto proposals * and execute transactions directly on contracts. */ address private guardianAddress; /***** Enums *****/ /** * @notice All Proposal Outcome states. * InProgress - Proposal is active and can be voted on. * Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed. * ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed. * QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed. * ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed. * Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running. * This status is transiently used inside that function to prevent re-entrancy. * Vetoed - Proposal was vetoed by Guardian. * TargetContractAddressChanged - Proposal considered invalid since target contract address changed * TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed */ enum Outcome { InProgress, Rejected, ApprovedExecuted, QuorumNotMet, ApprovedExecutionFailed, Evaluating, Vetoed, TargetContractAddressChanged, TargetContractCodeHashChanged } /** * @notice All Proposal Vote states for a voter. * None - The default state, for any account that has not previously voted on this Proposal. * No - The account voted No on this Proposal. * Yes - The account voted Yes on this Proposal. * @dev Enum values map to uints, so first value in Enum always is 0. */ enum Vote {None, No, Yes} struct Proposal { uint256 proposalId; address proposer; uint256 submissionBlockNumber; bytes32 targetContractRegistryKey; address targetContractAddress; uint256 callValue; string functionSignature; bytes callData; Outcome outcome; uint256 voteMagnitudeYes; uint256 voteMagnitudeNo; uint256 numVotes; mapping(address => Vote) votes; mapping(address => uint256) voteMagnitudes; bytes32 contractHash; } /***** Proposal storage *****/ /// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed. uint256 lastProposalId = 0; /// @notice mapping of proposalId to Proposal struct with all proposal state mapping(uint256 => Proposal) proposals; /// @notice array of proposals with InProgress state uint256[] inProgressProposals; /***** Events *****/ event ProposalSubmitted( uint256 indexed _proposalId, address indexed _proposer, string _name, string _description ); event ProposalVoteSubmitted( uint256 indexed _proposalId, address indexed _voter, Vote indexed _vote, uint256 _voterStake ); event ProposalVoteUpdated( uint256 indexed _proposalId, address indexed _voter, Vote indexed _vote, uint256 _voterStake, Vote _previousVote ); event ProposalOutcomeEvaluated( uint256 indexed _proposalId, Outcome indexed _outcome, uint256 _voteMagnitudeYes, uint256 _voteMagnitudeNo, uint256 _numVotes ); event ProposalTransactionExecuted( uint256 indexed _proposalId, bool indexed _success, bytes _returnData ); event GuardianTransactionExecuted( address indexed _targetContractAddress, uint256 _callValue, string indexed _functionSignature, bytes indexed _callData, bytes _returnData ); event ProposalVetoed(uint256 indexed _proposalId); event RegistryAddressUpdated(address indexed _newRegistryAddress); event GuardianshipTransferred(address indexed _newGuardianAddress); event VotingPeriodUpdated(uint256 indexed _newVotingPeriod); event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay); event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent); event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals); /** * @notice Initialize the Governance contract * @dev _votingPeriod <= DelegateManager.undelegateLockupDuration * @dev stakingAddress must be initialized separately after Staking contract is deployed * @param _registryAddress - address of the registry proxy contract * @param _votingPeriod - period in blocks for which a governance proposal is open for voting * @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed * @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid * @param _maxInProgressProposals - max number of InProgress proposals possible at once * @param _guardianAddress - address of account that has special Governance permissions */ function initialize( address _registryAddress, uint256 _votingPeriod, uint256 _executionDelay, uint256 _votingQuorumPercent, uint16 _maxInProgressProposals, address _guardianAddress ) public initializer { require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY); registry = Registry(_registryAddress); require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD); votingPeriod = _votingPeriod; // executionDelay does not have to be non-zero executionDelay = _executionDelay; require( _maxInProgressProposals > 0, "Governance: Requires non-zero _maxInProgressProposals" ); maxInProgressProposals = _maxInProgressProposals; require( _votingQuorumPercent > 0 && _votingQuorumPercent <= 100, ERROR_INVALID_VOTING_QUORUM ); votingQuorumPercent = _votingQuorumPercent; require( _guardianAddress != address(0x00), "Governance: Requires non-zero _guardianAddress" ); guardianAddress = _guardianAddress; //Guardian address becomes the only party InitializableV2.initialize(); } // ========================================= Governance Actions ========================================= /** * @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake. * total active stake = total active deployer stake + total active delegator stake * * @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted * * @param _targetContractRegistryKey - Registry key for the contract concerning this proposal * @param _callValue - amount of wei to pass with function call if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful * @param _name - Text name of proposal to be emitted in event * @param _description - Text description of proposal to be emitted in event * * @return - ID of new proposal */ function submitProposal( bytes32 _targetContractRegistryKey, uint256 _callValue, string calldata _functionSignature, bytes calldata _callData, string calldata _name, string calldata _description ) external returns (uint256) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); address proposer = msg.sender; // Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission require( this.inProgressProposalsAreUpToDate(), "Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated." ); // Require new proposal submission would not push number of InProgress proposals over max number require( inProgressProposals.length < maxInProgressProposals, "Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire." ); // Require proposer has non-zero total active stake or is guardian address require( _calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress, "Governance: Proposer must be address with non-zero total active stake or be guardianAddress." ); // Require _targetContractRegistryKey points to a valid registered contract address targetContractAddress = registry.getContract(_targetContractRegistryKey); require( targetContractAddress != address(0x00), "Governance: _targetContractRegistryKey must point to valid registered contract" ); // Signature cannot be empty require( bytes(_functionSignature).length != 0, "Governance: _functionSignature cannot be empty." ); // Require non-zero description length require(bytes(_description).length > 0, "Governance: _description length must be > 0"); // Require non-zero name length require(bytes(_name).length > 0, "Governance: _name length must be > 0"); // set proposalId uint256 newProposalId = lastProposalId.add(1); // Store new Proposal obj in proposals mapping proposals[newProposalId] = Proposal({ proposalId: newProposalId, proposer: proposer, submissionBlockNumber: block.number, targetContractRegistryKey: _targetContractRegistryKey, targetContractAddress: targetContractAddress, callValue: _callValue, functionSignature: _functionSignature, callData: _callData, outcome: Outcome.InProgress, voteMagnitudeYes: 0, voteMagnitudeNo: 0, numVotes: 0, contractHash: _getCodeHash(targetContractAddress) /* votes: mappings are auto-initialized to default state */ /* voteMagnitudes: mappings are auto-initialized to default state */ }); // Append new proposalId to inProgressProposals array inProgressProposals.push(newProposalId); emit ProposalSubmitted( newProposalId, proposer, _name, _description ); lastProposalId = newProposalId; return newProposalId; } /** * @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake. * @param _proposalId - id of the proposal this vote is for * @param _vote - can be either {Yes, No} from Vote enum. No other values allowed */ function submitVote(uint256 _proposalId, Vote _vote) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); address voter = msg.sender; // Require proposal votingPeriod is still active uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod); require( block.number > submissionBlockNumber && block.number <= endBlockNumber, "Governance: Proposal votingPeriod has ended" ); // Require voter has non-zero total active stake uint256 voterActiveStake = _calculateAddressActiveStake(voter); require( voterActiveStake > 0, "Governance: Voter must be address with non-zero total active stake." ); // Require previous vote is None require( proposals[_proposalId].votes[voter] == Vote.None, "Governance: To update previous vote, call updateVote()" ); // Require vote is either Yes or No require( _vote == Vote.Yes || _vote == Vote.No, "Governance: Can only submit a Yes or No vote" ); // Record vote proposals[_proposalId].votes[voter] = _vote; // Record voteMagnitude for voter proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake; // Update proposal cumulative vote magnitudes if (_vote == Vote.Yes) { _increaseVoteMagnitudeYes(_proposalId, voterActiveStake); } else { _increaseVoteMagnitudeNo(_proposalId, voterActiveStake); } // Increment proposal numVotes proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1); emit ProposalVoteSubmitted( _proposalId, voter, _vote, voterActiveStake ); } /** * @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake. * @param _proposalId - id of the proposal this vote is for * @param _vote - can be either {Yes, No} from Vote enum. No other values allowed */ function updateVote(uint256 _proposalId, Vote _vote) external { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); address voter = msg.sender; // Require proposal votingPeriod is still active uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod); require( block.number > submissionBlockNumber && block.number <= endBlockNumber, "Governance: Proposal votingPeriod has ended" ); // Retrieve previous vote Vote previousVote = proposals[_proposalId].votes[voter]; // Require previous vote is not None require( previousVote != Vote.None, "Governance: To submit new vote, call submitVote()" ); // Require vote is either Yes or No require( _vote == Vote.Yes || _vote == Vote.No, "Governance: Can only submit a Yes or No vote" ); // Record updated vote proposals[_proposalId].votes[voter] = _vote; // Update vote magnitudes, using vote magnitude from when previous vote was submitted uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter]; if (previousVote == Vote.Yes && _vote == Vote.No) { _decreaseVoteMagnitudeYes(_proposalId, voteMagnitude); _increaseVoteMagnitudeNo(_proposalId, voteMagnitude); } else if (previousVote == Vote.No && _vote == Vote.Yes) { _decreaseVoteMagnitudeNo(_proposalId, voteMagnitude); _increaseVoteMagnitudeYes(_proposalId, voteMagnitude); } // If _vote == previousVote, no changes needed to vote magnitudes. // Do not update numVotes emit ProposalVoteUpdated( _proposalId, voter, _vote, voteMagnitude, previousVote ); } /** * @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and * execute the proposal if voting quorum met & vote passes. * To pass, stake-weighted vote must be > 50% Yes. * @dev Requires that caller is an active staker at the time the proposal is created * @param _proposalId - id of the proposal * @return Outcome of proposal evaluation */ function evaluateProposalOutcome(uint256 _proposalId) external returns (Outcome) { _requireIsInitialized(); _requireStakingAddressIsSet(); _requireServiceProviderFactoryAddressIsSet(); _requireDelegateManagerAddressIsSet(); _requireValidProposalId(_proposalId); // Require proposal has not already been evaluated. require( proposals[_proposalId].outcome == Outcome.InProgress, "Governance: Can only evaluate InProgress proposal." ); // Re-entrancy should not be possible here since this switches the status of the // proposal to 'Evaluating' so it should fail the status is 'InProgress' check proposals[_proposalId].outcome = Outcome.Evaluating; // Require proposal votingPeriod + executionDelay have ended. uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber; uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay); require( block.number > endBlockNumber, "Governance: Proposal votingPeriod & executionDelay must end before evaluation." ); address targetContractAddress = registry.getContract( proposals[_proposalId].targetContractRegistryKey ); Outcome outcome; // target contract address changed -> close proposal without execution. if (targetContractAddress != proposals[_proposalId].targetContractAddress) { outcome = Outcome.TargetContractAddressChanged; } // target contract code hash changed -> close proposal without execution. else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) { outcome = Outcome.TargetContractCodeHashChanged; } // voting quorum not met -> close proposal without execution. else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) { outcome = Outcome.QuorumNotMet; } // votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal. else if ( proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo ) { (bool success, bytes memory returnData) = _executeTransaction( targetContractAddress, proposals[_proposalId].callValue, proposals[_proposalId].functionSignature, proposals[_proposalId].callData ); emit ProposalTransactionExecuted( _proposalId, success, returnData ); // Proposal outcome depends on success of transaction execution. if (success) { outcome = Outcome.ApprovedExecuted; } else { outcome = Outcome.ApprovedExecutionFailed; } } // votingQuorumPercent met & vote did not pass -> close proposal without transaction execution. else { outcome = Outcome.Rejected; } // This records the final outcome in the proposals mapping proposals[_proposalId].outcome = outcome; // Remove from inProgressProposals array _removeFromInProgressProposals(_proposalId); emit ProposalOutcomeEvaluated( _proposalId, outcome, proposals[_proposalId].voteMagnitudeYes, proposals[_proposalId].voteMagnitudeNo, proposals[_proposalId].numVotes ); return outcome; } /** * @notice Action limited to the guardian address that can veto a proposal * @param _proposalId - id of the proposal */ function vetoProposal(uint256 _proposalId) external { _requireIsInitialized(); _requireValidProposalId(_proposalId); require( msg.sender == guardianAddress, "Governance: Only guardian can veto proposals." ); require( proposals[_proposalId].outcome == Outcome.InProgress, "Governance: Cannot veto inactive proposal." ); proposals[_proposalId].outcome = Outcome.Vetoed; // Remove from inProgressProposals array _removeFromInProgressProposals(_proposalId); emit ProposalVetoed(_proposalId); } // ========================================= Config Setters ========================================= /** * @notice Set the Staking address * @dev Only callable by self via _executeTransaction * @param _stakingAddress - address for new Staking contract */ function setStakingAddress(address _stakingAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress"); stakingAddress = _stakingAddress; } /** * @notice Set the ServiceProviderFactory address * @dev Only callable by self via _executeTransaction * @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract */ function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _serviceProviderFactoryAddress != address(0x00), "Governance: Requires non-zero _serviceProviderFactoryAddress" ); serviceProviderFactoryAddress = _serviceProviderFactoryAddress; } /** * @notice Set the DelegateManager address * @dev Only callable by self via _executeTransaction * @param _delegateManagerAddress - address for new DelegateManager contract */ function setDelegateManagerAddress(address _delegateManagerAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _delegateManagerAddress != address(0x00), "Governance: Requires non-zero _delegateManagerAddress" ); delegateManagerAddress = _delegateManagerAddress; } /** * @notice Set the voting period for a Governance proposal * @dev Only callable by self via _executeTransaction * @param _votingPeriod - new voting period */ function setVotingPeriod(uint256 _votingPeriod) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD); votingPeriod = _votingPeriod; emit VotingPeriodUpdated(_votingPeriod); } /** * @notice Set the voting quorum percentage for a Governance proposal * @dev Only callable by self via _executeTransaction * @param _votingQuorumPercent - new voting period */ function setVotingQuorumPercent(uint256 _votingQuorumPercent) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _votingQuorumPercent > 0 && _votingQuorumPercent <= 100, ERROR_INVALID_VOTING_QUORUM ); votingQuorumPercent = _votingQuorumPercent; emit VotingQuorumPercentUpdated(_votingQuorumPercent); } /** * @notice Set the Registry address * @dev Only callable by self via _executeTransaction * @param _registryAddress - address for new Registry contract */ function setRegistryAddress(address _registryAddress) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY); registry = Registry(_registryAddress); emit RegistryAddressUpdated(_registryAddress); } /** * @notice Set the max number of concurrent InProgress proposals * @dev Only callable by self via _executeTransaction * @param _newMaxInProgressProposals - new value for maxInProgressProposals */ function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); require( _newMaxInProgressProposals > 0, "Governance: Requires non-zero _newMaxInProgressProposals" ); maxInProgressProposals = _newMaxInProgressProposals; emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals); } /** * @notice Set the execution delay for a proposal * @dev Only callable by self via _executeTransaction * @param _newExecutionDelay - new value for executionDelay */ function setExecutionDelay(uint256 _newExecutionDelay) external { _requireIsInitialized(); require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE); // executionDelay does not have to be non-zero executionDelay = _newExecutionDelay; emit ExecutionDelayUpdated(_newExecutionDelay); } // ========================================= Guardian Actions ========================================= /** * @notice Allows the guardianAddress to execute protocol actions * @param _targetContractRegistryKey - key in registry of target contract * @param _callValue - amount of wei if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful */ function guardianExecuteTransaction( bytes32 _targetContractRegistryKey, uint256 _callValue, string calldata _functionSignature, bytes calldata _callData ) external { _requireIsInitialized(); require( msg.sender == guardianAddress, "Governance: Only guardian." ); // _targetContractRegistryKey must point to a valid registered contract address targetContractAddress = registry.getContract(_targetContractRegistryKey); require( targetContractAddress != address(0x00), "Governance: _targetContractRegistryKey must point to valid registered contract" ); // Signature cannot be empty require( bytes(_functionSignature).length != 0, "Governance: _functionSignature cannot be empty." ); (bool success, bytes memory returnData) = _executeTransaction( targetContractAddress, _callValue, _functionSignature, _callData ); require(success, "Governance: Transaction failed."); emit GuardianTransactionExecuted( targetContractAddress, _callValue, _functionSignature, _callData, returnData ); } /** * @notice Change the guardian address * @dev Only callable by current guardian * @param _newGuardianAddress - new guardian address */ function transferGuardianship(address _newGuardianAddress) external { _requireIsInitialized(); require( msg.sender == guardianAddress, "Governance: Only guardian." ); guardianAddress = _newGuardianAddress; emit GuardianshipTransferred(_newGuardianAddress); } // ========================================= Getter Functions ========================================= /** * @notice Get proposal information by proposal Id * @param _proposalId - id of proposal */ function getProposalById(uint256 _proposalId) external view returns ( uint256 proposalId, address proposer, uint256 submissionBlockNumber, bytes32 targetContractRegistryKey, address targetContractAddress, uint256 callValue, string memory functionSignature, bytes memory callData, Outcome outcome, uint256 voteMagnitudeYes, uint256 voteMagnitudeNo, uint256 numVotes ) { _requireIsInitialized(); _requireValidProposalId(_proposalId); Proposal memory proposal = proposals[_proposalId]; return ( proposal.proposalId, proposal.proposer, proposal.submissionBlockNumber, proposal.targetContractRegistryKey, proposal.targetContractAddress, proposal.callValue, proposal.functionSignature, proposal.callData, proposal.outcome, proposal.voteMagnitudeYes, proposal.voteMagnitudeNo, proposal.numVotes /** @notice - votes mapping cannot be returned by external function */ /** @notice - voteMagnitudes mapping cannot be returned by external function */ /** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */ ); } /** * @notice Get proposal target contract hash by proposalId * @dev This is a separate function because the getProposalById returns too many variables already and by adding more, you get the error `InternalCompilerError: Stack too deep, try using fewer variables` * @param _proposalId - id of proposal */ function getProposalTargetContractHash(uint256 _proposalId) external view returns (bytes32) { _requireIsInitialized(); _requireValidProposalId(_proposalId); return (proposals[_proposalId].contractHash); } /** * @notice Get vote direction and vote magnitude for a given proposal and voter * @param _proposalId - id of the proposal * @param _voter - address of the voter we want to check * @return returns vote direction and magnitude if valid vote, else default values */ function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter) external view returns (Vote vote, uint256 voteMagnitude) { _requireIsInitialized(); _requireValidProposalId(_proposalId); return ( proposals[_proposalId].votes[_voter], proposals[_proposalId].voteMagnitudes[_voter] ); } /// @notice Get the contract Guardian address function getGuardianAddress() external view returns (address) { _requireIsInitialized(); return guardianAddress; } /// @notice Get the Staking address function getStakingAddress() external view returns (address) { _requireIsInitialized(); return stakingAddress; } /// @notice Get the ServiceProviderFactory address function getServiceProviderFactoryAddress() external view returns (address) { _requireIsInitialized(); return serviceProviderFactoryAddress; } /// @notice Get the DelegateManager address function getDelegateManagerAddress() external view returns (address) { _requireIsInitialized(); return delegateManagerAddress; } /// @notice Get the contract voting period function getVotingPeriod() external view returns (uint256) { _requireIsInitialized(); return votingPeriod; } /// @notice Get the contract voting quorum percent function getVotingQuorumPercent() external view returns (uint256) { _requireIsInitialized(); return votingQuorumPercent; } /// @notice Get the registry address function getRegistryAddress() external view returns (address) { _requireIsInitialized(); return address(registry); } /// @notice Used to check if is governance contract before setting governance address in other contracts function isGovernanceAddress() external pure returns (bool) { return true; } /// @notice Get the max number of concurrent InProgress proposals function getMaxInProgressProposals() external view returns (uint16) { _requireIsInitialized(); return maxInProgressProposals; } /// @notice Get the proposal execution delay function getExecutionDelay() external view returns (uint256) { _requireIsInitialized(); return executionDelay; } /// @notice Get the array of all InProgress proposal Ids function getInProgressProposals() external view returns (uint256[] memory) { _requireIsInitialized(); return inProgressProposals; } /** * @notice Returns false if any proposals in inProgressProposals array are evaluatable * Evaluatable = proposals with closed votingPeriod * @dev Is public since its called internally in `submitProposal()` as well as externally in UI */ function inProgressProposalsAreUpToDate() external view returns (bool) { _requireIsInitialized(); // compare current block number against endBlockNumber of each proposal for (uint256 i = 0; i < inProgressProposals.length; i++) { if ( block.number > (proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay) ) { return false; } } return true; } // ========================================= Internal Functions ========================================= /** * @notice Execute a transaction attached to a governance proposal * @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity * function calls here, but have chosen to keep this code with those issues in mind. All governance * proposals go through a voting process, and all will be reviewed carefully to ensure that they * adhere to the expected behaviors of this call - but adding restrictions here would limit the ability * of the governance system to do required work in a generic way. * @param _targetContractAddress - address of registry proxy contract to execute transaction on * @param _callValue - amount of wei if a token transfer is involved * @param _functionSignature - function signature of the function to be executed if proposal is successful * @param _callData - encoded value(s) to call function with if proposal is successful */ function _executeTransaction( address _targetContractAddress, uint256 _callValue, string memory _functionSignature, bytes memory _callData ) internal returns (bool success, bytes memory returnData) { bytes memory encodedCallData = abi.encodePacked( bytes4(keccak256(bytes(_functionSignature))), _callData ); (success, returnData) = ( // solium-disable-next-line security/no-call-value _targetContractAddress.call.value(_callValue)(encodedCallData) ); return (success, returnData); } function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeYes = ( proposals[_proposalId].voteMagnitudeYes.add(_voterStake) ); } function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeNo = ( proposals[_proposalId].voteMagnitudeNo.add(_voterStake) ); } function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeYes = ( proposals[_proposalId].voteMagnitudeYes.sub(_voterStake) ); } function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal { proposals[_proposalId].voteMagnitudeNo = ( proposals[_proposalId].voteMagnitudeNo.sub(_voterStake) ); } /** * @dev Can make O(1) by storing index pointer in proposals mapping. * Requires inProgressProposals to be 1-indexed, since all proposals that are not present * will have pointer set to 0. */ function _removeFromInProgressProposals(uint256 _proposalId) internal { uint256 index = 0; for (uint256 i = 0; i < inProgressProposals.length; i++) { if (inProgressProposals[i] == _proposalId) { index = i; break; } } // Swap proposalId to end of array + pop (deletes last elem + decrements array length) inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1]; inProgressProposals.pop(); } /** * @notice Returns true if voting quorum percentage met for proposal, else false. * @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking * @dev Eventual multiplication overflow: * (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation, * can sum to at most the entire token supply of 10^27 * With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest: * log(2^256/(10^27*100))/log(1.07) ~= 1635 * * @dev Note that quorum is evaluated based on total staked at proposal submission * not total staked at proposal evaluation, this is expected behavior */ function _quorumMet(Proposal memory proposal, Staking stakingContract) internal view returns (bool) { uint256 participation = ( (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo) .mul(100) .div(stakingContract.totalStakedAt(proposal.submissionBlockNumber)) ); return participation >= votingQuorumPercent; } // ========================================= Private Functions ========================================= function _requireStakingAddressIsSet() private view { require( stakingAddress != address(0x00), "Governance: stakingAddress is not set" ); } function _requireServiceProviderFactoryAddressIsSet() private view { require( serviceProviderFactoryAddress != address(0x00), "Governance: serviceProviderFactoryAddress is not set" ); } function _requireDelegateManagerAddressIsSet() private view { require( delegateManagerAddress != address(0x00), "Governance: delegateManagerAddress is not set" ); } function _requireValidProposalId(uint256 _proposalId) private view { require( _proposalId <= lastProposalId && _proposalId > 0, "Governance: Must provide valid non-zero _proposalId" ); } /** * Calculates and returns active stake for address * * Active stake = (active deployer stake + active delegator stake) * active deployer stake = (direct deployer stake - locked deployer stake) * locked deployer stake = amount of pending decreaseStakeRequest for address * active delegator stake = (total delegator stake - locked delegator stake) * locked delegator stake = amount of pending undelegateRequest for address */ function _calculateAddressActiveStake(address _address) private view returns (uint256) { ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress); DelegateManager delegateManager = DelegateManager(delegateManagerAddress); // Amount directly staked by address, if any, in ServiceProviderFactory (uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address); // Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory (uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address); // active deployer stake = (direct deployer stake - locked deployer stake) uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake); // Total amount delegated by address, if any, in DelegateManager uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address); // Amount of pending undelegateRequest for address, if any, in DelegateManager (,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address); // active delegator stake = (total delegator stake - locked delegator stake) uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake); // activeStake = (activeDeployerStake + activeDelegatorStake) uint256 activeStake = activeDeployerStake.add(activeDelegatorStake); return activeStake; } // solium-disable security/no-inline-assembly /** * @notice Helper function to generate the code hash for a contract address * @return contract code hash */ function _getCodeHash(address _contract) private view returns (bytes32) { bytes32 contractHash; assembly { contractHash := extcodehash(_contract) } return contractHash; } } contract EthRewardsManager is InitializableV2 { using SafeERC20 for ERC20; string private constant ERROR_TOKEN_NOT_CONTRACT = ( "EthRewardsManager: token is not a contract" ); string private constant ERROR_WORMHOLE_NOT_CONTRACT = ( "EthRewardsManager: wormhole is not a contract" ); string private constant ERROR_ONLY_GOVERNANCE = ( "EthRewardsManager: Only governance" ); address private governanceAddress; /// @dev ERC-20 token that will be used to stake with ERC20 internal audiusToken; Wormhole internal wormhole; bytes32 internal recipient; address[] internal antiAbuseOracleAddresses; /** * @notice Function to initialize the contract * @param _tokenAddress - address of ERC20 token * @param _governanceAddress - address for Governance proxy contract * @param _wormholeAddress - address for Wormhole contract * @param _recipient - solana address of recipient * @param _antiAbuseOracleAddresses - addresses for anti abuse oracle */ function initialize( address _tokenAddress, address _governanceAddress, address _wormholeAddress, bytes32 _recipient, address[] memory _antiAbuseOracleAddresses ) public initializer { require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT); require( Address.isContract(_wormholeAddress), ERROR_WORMHOLE_NOT_CONTRACT ); audiusToken = ERC20(_tokenAddress); wormhole = Wormhole(_wormholeAddress); recipient = _recipient; antiAbuseOracleAddresses = _antiAbuseOracleAddresses; _updateGovernanceAddress(_governanceAddress); InitializableV2.initialize(); } /** * @notice Set the Governance address * @dev Only callable by Governance address * @param _governanceAddress - address for new Governance contract */ function setGovernanceAddress(address _governanceAddress) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); _updateGovernanceAddress(_governanceAddress); } /** * @notice Set the recipient address * @dev Only callable by Governance address * @param _recipient - address for new recipient */ function setRecipientAddress(bytes32 _recipient) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); recipient = _recipient; } /** * @notice Set antiAbuseOracleAddresses * @dev Only callable by Governance address * @param _antiAbuseOracleAddresses - values of new anti abuse oracle addresses */ function setAntiAbuseOracleAddresses(address[] calldata _antiAbuseOracleAddresses) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); antiAbuseOracleAddresses = _antiAbuseOracleAddresses; } /* External functions */ /** * @notice Transfers to solana * @param arbiterFee - fee to pay wormhole arbiter * @param _nonce - nonce for wormhole */ function transferToSolana(uint256 arbiterFee, uint32 _nonce) external { _requireIsInitialized(); uint256 balance = audiusToken.balanceOf(address(this)); audiusToken.approve(address(wormhole), balance); wormhole.transferTokens( address(audiusToken), balance, 1, recipient, arbiterFee, _nonce ); } /** * @notice Get the token used by the contract * @return The token used by the contract */ function token() external view returns (address) { _requireIsInitialized(); return address(audiusToken); } /// @notice Get the Governance address function getGovernanceAddress() external view returns (address) { _requireIsInitialized(); return governanceAddress; } /// @notice Get the recipient address function getRecipientAddress() external view returns (bytes32) { _requireIsInitialized(); return recipient; } /// @notice Get the anti abuse oracle addresses function getAntiAbuseOracleAddresses() external view returns (address[] memory) { _requireIsInitialized(); return antiAbuseOracleAddresses; } // ========================================= Internal Functions ========================================= /** * @notice Set the governance address after confirming contract identity * @param _governanceAddress - Incoming governance address */ function _updateGovernanceAddress(address _governanceAddress) internal { require( Governance(_governanceAddress).isGovernanceAddress() == true, "EthRewardsManager: _governanceAddress is not a valid governance contract" ); governanceAddress = _governanceAddress; } }
Set the recipient address Only callable by Governance address _recipient - address for new recipient/
function setRecipientAddress(bytes32 _recipient) external { _requireIsInitialized(); require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE); recipient = _recipient; }
1,616,643
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /* * @title BARIS ATALAY * @dev Set & change owner * * @IMPORTANT Reward tokens to be distributed to the stakers must be deposited into the contract. * */ contract DynamicAssetStake is Context, Ownable{ event Stake(address indexed from, uint256 amount); event UnStake(address indexed from, uint256 amount); event YieldWithdraw(address indexed to); struct PendingRewardResponse{ // Model of showing pending awards bytes32 name; // Byte equivalent of the name of the pool token uint256 amount; // TODO... uint id; // Id of Reward } struct RewardDef{ address tokenAddress; // Contract Address of Reward token uint256 rewardPerSecond; // Accepted reward per second bytes32 name; // Byte equivalent of the name of the pool token uint8 feeRate; // Fee Rate for Reward Harvest uint id; // Id of Reward } struct PoolDef{ address tokenAddress; // Contract Address of Pool token uint rewardCount; // Amount of the reward to be won from the pool uint id; // Id of pool bool active; // Pool active status } struct PoolDefExt{ uint256 expiryTime; // The pool remains active until the set time uint256 createTime; // Pool creation time bytes32 name; // Byte equivalent of the name of the pool token } struct PoolVariable{ // Only owner can edit uint256 balanceFee; // Withdraw Fee for contract Owner; uint256 lastRewardTimeStamp; // Last date reward was calculated uint8 feeRate; // Fee Rate for UnStake } struct PoolRewardVariable{ uint256 accTokenPerShare; // Token share to be distributed to users uint256 balance; // Pool Contract Token Balance } // Info of each user struct UserDef{ address id; // Wallet Address of staker uint256 stakingBalance; // Amount of current staking balance uint256 startTime; // Staking start time } struct UserRewardInfo{ uint256 rewardBalance; } uint private stakeIDCounter; //Pool ID => PoolDef mapping(uint => PoolDef) public poolList; //Pool ID => Underused Pool information mapping(uint => PoolDefExt) public poolListExtras; //Pool ID => Pool Variable info mapping(uint => PoolVariable) public poolVariable; //Pool ID => (RewardIndex => RewardDef) mapping(uint => mapping(uint => RewardDef)) public poolRewardList; //Pool ID => (RewardIndex => PoolRewardVariable) mapping(uint => mapping(uint => PoolRewardVariable)) public poolRewardVariableInfo; //Pool ID => (RewardIndex => Amount of distributed reward to staker) mapping(uint => mapping(uint => uint)) public poolPaidOut; //Pool ID => Amount of Stake from User mapping(uint => uint) public poolTotalStake; //Pool ID => (User ID => User Info) mapping(uint => mapping(address => UserDef)) poolUserInfo; //Pool ID => (User ID => (Reward Id => Reward Info)) mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo; using SafeMath for uint; using SafeERC20 for IERC20; constructor(){ stakeIDCounter = 0; } /// @notice Updates the deserved rewards in the pool /// @param _stakeID Id of the stake pool function UpdatePoolRewardShare(uint _stakeID) internal virtual { uint256 lastTimeStamp = block.timestamp; PoolVariable storage selectedPoolVariable = poolVariable[_stakeID]; if (lastTimeStamp <= selectedPoolVariable.lastRewardTimeStamp) { lastTimeStamp = selectedPoolVariable.lastRewardTimeStamp; } if (poolTotalStake[_stakeID] == 0) { selectedPoolVariable.lastRewardTimeStamp = block.timestamp; return; } uint256 timeDiff = lastTimeStamp.sub(selectedPoolVariable.lastRewardTimeStamp); //..:: Calculating the reward shares of the pool ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][i].rewardPerSecond); poolRewardVariableInfo[_stakeID][i].accTokenPerShare = poolRewardVariableInfo[_stakeID][i].accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } //..:: Calculating the reward shares of the pool ::.. selectedPoolVariable.lastRewardTimeStamp = block.timestamp; } /// @notice Lists the rewards of the transacting user in the pool /// @param _stakeID Id of the stake pool /// @return Reward model list function showPendingReward(uint _stakeID) public virtual view returns(PendingRewardResponse[] memory) { UserDef memory user = poolUserInfo[_stakeID][_msgSender()]; uint256 lastTimeStamp = block.timestamp; uint rewardCount = poolList[_stakeID].rewardCount; PendingRewardResponse[] memory result = new PendingRewardResponse[](rewardCount); for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint _accTokenPerShare = poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare; if (lastTimeStamp > poolVariable[_stakeID].lastRewardTimeStamp && poolTotalStake[_stakeID] != 0) { uint256 timeDiff = lastTimeStamp.sub(poolVariable[_stakeID].lastRewardTimeStamp); uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][RewardIndex].rewardPerSecond); _accTokenPerShare = _accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } result[RewardIndex] = PendingRewardResponse({ id: RewardIndex, name: poolRewardList[_stakeID][RewardIndex].name, amount: user.stakingBalance .mul(_accTokenPerShare) .div(1e36) .sub(poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance) }); } return result; } /// @notice Withdraw assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of withdraw asset function unStake(uint _stakeID, uint256 _amount) public { require(_msgSender() != address(0), "Stake: Staker address not specified!"); //IERC20 selectedToken = getStakeContract(_stakeID); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; require(user.stakingBalance > 0, "Stake: does not have staking balance"); // Amount leak control if (_amount > user.stakingBalance) _amount = user.stakingBalance; // "_amount" removed to Total staked value by Pool ID if (_amount > 0) poolTotalStake[_stakeID] = poolTotalStake[_stakeID].sub(_amount); UpdatePoolRewardShare(_stakeID); sendPendingReward(_stakeID, user, true); uint256 unStakeFee; if (poolVariable[_stakeID].feeRate > 0) unStakeFee = _amount .mul(poolVariable[_stakeID].feeRate) .div(100); // Calculated unStake amount after commission deducted uint256 finalUnStakeAmount = _amount.sub(unStakeFee); // ..:: Updated last user info ::.. user.startTime = block.timestamp; user.stakingBalance = user.stakingBalance.sub(_amount); // ..:: Updated last user info ::.. if (finalUnStakeAmount > 0) getStakeContract(_stakeID).safeTransfer(_msgSender(), finalUnStakeAmount); emit UnStake(_msgSender(), _amount); } /// @notice Structure that calculates rewards to be distributed for users /// @param _stakeID Id of the stake pool /// @param _user Staker info /// @param _subtractFee If the value is true, the commission is subtracted when calculating the reward. function sendPendingReward(uint _stakeID, UserDef memory _user, bool _subtractFee) private { // ..:: Pending reward will be calculate and add to transferAmount, before transfer unStake amount ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint256 userRewardedBalance = poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance; uint pendingAmount = _user.stakingBalance .mul(poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare) .div(1e36) .sub(userRewardedBalance); if (pendingAmount > 0) { uint256 finalRewardAmount = pendingAmount; if (_subtractFee){ uint256 pendingRewardFee; if (poolRewardList[_stakeID][RewardIndex].feeRate > 0) pendingRewardFee = pendingAmount .mul(poolRewardList[_stakeID][RewardIndex].feeRate) .div(100); // Commission fees received are recorded for reporting poolVariable[_stakeID].balanceFee = poolVariable[_stakeID].balanceFee.add(pendingRewardFee); // Calculated reward after commission deducted finalRewardAmount = pendingAmount.sub(pendingRewardFee); } //Reward distribution getRewardTokenContract(_stakeID, RewardIndex).safeTransfer(_msgSender(), finalRewardAmount); // Updating balance pending to be distributed from contract to users poolRewardVariableInfo[_stakeID][RewardIndex].balance = poolRewardVariableInfo[_stakeID][RewardIndex].balance.sub(pendingAmount); // The amount distributed to users is reported poolPaidOut[_stakeID][RewardIndex] = poolPaidOut[_stakeID][RewardIndex].add(pendingAmount); } } } /// @notice Deposits assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of deposit asset function stake(uint _stakeID, uint256 _amount) public{ IERC20 selectedToken = getStakeContract(_stakeID); require(selectedToken.allowance(_msgSender(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0 && selectedToken.balanceOf(_msgSender()) >= _amount, "Stake: You cannot stake zero tokens"); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); UpdatePoolRewardShare(_stakeID); if (user.stakingBalance > 0) sendPendingReward(_stakeID, user, false); // "_amount" added to Total staked value by Pool ID poolTotalStake[_stakeID] = poolTotalStake[_stakeID].add(_amount); // "_amount" added to USER Total staked value by Pool ID user.stakingBalance = user.stakingBalance.add(_amount); // ..:: Calculating the rewards user pool deserve ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { poolUserRewardInfo[_stakeID][_msgSender()][i].rewardBalance = user.stakingBalance.mul(poolRewardVariableInfo[_stakeID][i].accTokenPerShare).div(1e36); } // ..:: Calculating the rewards user pool deserve ::.. emit Stake(_msgSender(), _amount); } /// @notice Returns staked token balance by pool id /// @param _stakeID Id of the stake pool /// @param _account Address of the staker /// @return Count of staked balance function balanceOf(uint _stakeID, address _account) public view returns (uint256) { return poolUserInfo[_stakeID][_account].stakingBalance; } /// @notice Returns Stake Poll Contract casted IERC20 interface by pool id /// @param _stakeID Id of the stake pool function getStakeContract(uint _stakeID) internal view returns(IERC20){ require(poolListExtras[_stakeID].name!="", "Stake: Selected contract is not valid"); require(poolList[_stakeID].active,"Stake: Selected contract is not active"); return IERC20(poolList[_stakeID].tokenAddress); } /// @notice Returns rewarded token address /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return Token contract function getRewardTokenContract(uint _stakeID, uint _rewardID) internal view returns(IERC20){ return IERC20(poolRewardList[_stakeID][_rewardID].tokenAddress); } /// @notice Checks the address has a stake /// @param _stakeID Id of the stake pool /// @param _user Address of the staker /// @return Value of stake status function isStaking(uint _stakeID, address _user) view public returns(bool){ return poolUserInfo[_stakeID][_user].stakingBalance > 0; } /// @notice Returns stake asset list of active function getPoolList() public view returns(PoolDef[] memory, PoolDefExt[] memory){ uint length = stakeIDCounter; PoolDef[] memory result = new PoolDef[](length); PoolDefExt[] memory resultExt = new PoolDefExt[](length); for (uint i=0; i<length; i++) { result[i] = poolList[i]; resultExt[i] = poolListExtras[i]; } return (result, resultExt); } /// @notice Returns the pool's reward definition information /// @param _stakeID Id of the stake pool /// @return List of pool's reward definition function getPoolRewardDefList(uint _stakeID) public view returns(RewardDef[] memory){ uint length = poolList[_stakeID].rewardCount; RewardDef[] memory result = new RewardDef[](length); for (uint i=0; i<length; i++) { result[i] = poolRewardList[_stakeID][i]; } return result; } /// @notice Returns the pool's reward definition information by pool id /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return pool's reward definition function getPoolRewardDef(uint _stakeID, uint _rewardID) public view returns(RewardDef memory, PoolRewardVariable memory){ return (poolRewardList[_stakeID][_rewardID], poolRewardVariableInfo[_stakeID][_rewardID]); } /// @notice Returns stake pool /// @param _stakeID Id of the stake pool /// @return Definition of pool function getPoolDefByID(uint _stakeID) public view returns(PoolDef memory){ require(poolListExtras[_stakeID].name!="", "Stake: Stake Asset is not valid"); return poolList[_stakeID]; } /// @notice Adds new stake def to the pool /// @param _poolAddress Address of the token pool /// @param _poolName Name of the token pool /// @param _rewards Rewards for the stakers function addNewStakePool(address _poolAddress, bytes32 _poolName, RewardDef[] memory _rewards) onlyOwner public returns(uint){ require(_poolAddress != address(0), "Stake: New Staking Pool address not valid"); require(_poolName != "", "Stake: New Staking Pool name not valid"); uint length = _rewards.length; for (uint i=0; i<length; i++) { _rewards[i].id = i; poolRewardList[stakeIDCounter][i] = _rewards[i]; } poolList[stakeIDCounter] = PoolDef(_poolAddress, length, stakeIDCounter, false); poolListExtras[stakeIDCounter] = PoolDefExt(block.timestamp, 0, _poolName); poolVariable[stakeIDCounter] = PoolVariable(0, 0, 0); stakeIDCounter++; return stakeIDCounter.sub(1); } /// @notice Disables stake pool for user /// @param _stakeID Id of the stake pool function disableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active,"Stake: Contract is already disabled"); poolList[_stakeID].active = false; } /// @notice Enables stake pool for user /// @param _stakeID Id of the stake pool function enableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active==false,"Stake: Contract is already enabled"); poolList[_stakeID].active = true; } /// @notice Returns pool list count /// @return Count of pool list function getPoolCount() public view returns(uint){ return stakeIDCounter; } /// @notice The contract owner adds the reward she shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0, "Stake: You cannot stake zero tokens"); require(address(this) != address(0), "Stake: Storage address did not set"); // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount); return true; } /// @notice The contract owner takes back the reward shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount); IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); selectedToken.safeTransfer(_msgSender(), _amount); return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _rewardPerSecond New staking reward per second function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same."); reward.rewardPerSecond = _rewardPerSecond; return true; } /// @return Returns number of reward to be distributed per second by pool id function getRewardPerSecond(uint _stakeID, uint _rewardID) public view returns(uint256){ return poolRewardList[_stakeID][_rewardID].rewardPerSecond; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _feeRate New reward harvest fee function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same."); reward.feeRate = _feeRate; return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _feeRate New unStake fee function updateUnStakeFeeRate(uint _stakeID, uint8 _feeRate) public onlyOwner returns(bool){ PoolVariable storage def = poolVariable[_stakeID]; require(def.feeRate != _feeRate, "UnStake FeeRate no change! Because it is same."); def.feeRate = _feeRate; return true; } /// @return Returns commission rate for Unstake transaction function getUnStakeFeeRate(uint _stakeID)public view returns(uint8){ return poolVariable[_stakeID].feeRate; } /// @return Returns blockchain time function getTime() public view returns(uint256){ return block.timestamp; } }
The contract owner takes back the reward shared with the users here _stakeID Id of the stake pool _rewardID Id of the reward _amount Amount of deposit to reward
function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount); IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); selectedToken.safeTransfer(_msgSender(), _amount); return true; }
13,084,411
pragma solidity ^0.8.0; // File: @openzeppelin/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/introspection/IERC165.sol /** * @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 /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.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); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.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 () { // 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; } } // File: @openzeppelin/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol /** * @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)))); } } // File: @openzeppelin/contracts/utils/Strings.sol /** * @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); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.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_) { _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 { } } // File: @openzeppelin/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/CryptoCopyCats.sol /** * @title CryptoCopyCats contract * @dev Extends ERC721 Non-Fungible Token Standard basic implementation */ contract CryptoCopyCats is ERC721, Ownable { using SafeMath for uint256; uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public maxToMint; uint256 public MAX_CRYPTO_COPY_CATS_SUPPLY; uint256 public REVEAL_TIMESTAMP; string private prerevealURI; string private specialTokenURI; string public PROVENANCE_HASH = ""; bool public saleIsActive; bool public whitelistActive; bytes32[] _rootHash; address wallet1; address wallet2; mapping(uint256 => uint256) private mintNumberToSpecialToken; mapping(uint256 => uint256) private replacedTokenNumber; mapping(address => uint256) public numberOfWhitelistMints; uint256 maxWhitelistMints; uint256 maxSpecialTokens; uint256 numberOfSpecialTokensMinted; uint256 public discountPrice; uint256 public fullPrice; constructor() ERC721("Crypto Copy Cats", "CCCATS") { MAX_CRYPTO_COPY_CATS_SUPPLY = 2510; REVEAL_TIMESTAMP = block.timestamp + 3 days; //block.timestamp + 3 days; specialTokenURI = "https://cryptocopycats.mypinata.cloud/ipfs/QmcP7jLdm6vEs5jFwvUkWUJRBwzcTW6wwtLtVCvvuS6uBT"; prerevealURI = "https://cryptocopycats.mypinata.cloud/ipfs/QmSe33Sr6E5oDoCLvzouaLzJ8y3wiFgevkRmTQnAnrwGcm"; discountPrice = 65000000000000000; // 0.065 Ether fullPrice = 75000000000000000; // 0.075 Ether numberOfSpecialTokensMinted = 0; maxSpecialTokens = 10; maxToMint = 4; maxWhitelistMints = 4; saleIsActive = false; whitelistActive = false; wallet1 = 0x6F10Cdb4901bA272dabbF7a6343A8FE43ec7d460; // ccc payout wallet wallet2 = 0xaf6e1747779744c1CE875A6463e28A5086084ae7; // byt payout wallet _rootHash = new bytes32[](2); _rootHash[0] = 0x435bffa06fdde9f30f2df9afc8937f180217f3a782ef6aa88f0c39326ed0f4b7; _rootHash[1] = 0x1736b74100da5d87fc309b6fb4e084dbd9d21a488951d37cab89c323ebbfb483; } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function isTokenEthRedeemable(uint256 tokenId) external view returns(bool) { require(startingIndex > 0, "Tokens have not revealed yet"); if(mintNumberToSpecialToken[tokenId] > 0) { return true; } return false; } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function updateRootHash(bytes32 rootHash) external onlyOwner { _rootHash[1] = rootHash; } /** * Set whitelist price to mint a Crypto Copy Cat. */ function setDiscountPrice(uint256 _price) external onlyOwner { discountPrice = _price; } /** * Set public price to mint a Crypto Copy Cat. */ function setFullPrice(uint256 _price) external onlyOwner { fullPrice = _price; } function getTotalWhitelistPrice(uint256 numberOfTokens) internal view returns(uint256) { uint256 ownedTokens = numberOfWhitelistMints[_msgSender()]; if (ownedTokens == 0) { return discountPrice.mul(numberOfTokens - 1); } else { return discountPrice.mul(numberOfTokens); } } /** * Set maximum count to mint per txn. */ function setMaxToMint(uint256 _maxValue) external onlyOwner { maxToMint = _maxValue; } /** * Mint Crypto Copy Cat by owner. */ function reserveCryptoCopyCat(address _to, uint256 _numberOfTokens) external onlyOwner { require(_to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; //Mint address, 0 on first mint //Supply is 1 so mint tokenId = 1 (which is the 2nd token) for (i = 0; i < _numberOfTokens; i++) { _safeMint(_to, supply + i); } } /** * Set reveal timestamp when finished the sale. */ function setRevealTimestamp(uint256 _revealTimeStamp) external onlyOwner { REVEAL_TIMESTAMP = _revealTimeStamp; } function setBaseURI(string memory baseURI) external onlyOwner { _setBaseURI(baseURI); } /** * External function to set the prereveal URI for all token IDs. * This is the URI that is shown on each token until the REVEAL_TIMESTAMP * is surpassed. */ function setPrerevealURI(string memory prerevealURI_) external onlyOwner { prerevealURI = prerevealURI_; } /** * Returns the proper tokenURI only after the startingIndex is finalized. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if(startingIndex != 0 && block.timestamp >= REVEAL_TIMESTAMP) { string memory base = baseURI(); if (mintNumberToSpecialToken[tokenId] != 0) { return specialTokenURI; } else if (replacedTokenNumber[tokenId] != 0){ return string(abi.encodePacked(base, uint2str(replacedTokenNumber[tokenId]))); } else { string memory tokenURIWithOffset = uint2str(((tokenId + startingIndex) % MAX_CRYPTO_COPY_CATS_SUPPLY)); return string(abi.encodePacked(base, tokenURIWithOffset)); } } else { return prerevealURI; } } /* * Pause sale if active, make active if paused */ function setSaleState() external onlyOwner { saleIsActive = !saleIsActive; } /* * Pause whitelist if active, make active if paused */ function setWhitelistState() external onlyOwner { whitelistActive = !whitelistActive; } function isSpecialToken(uint256 tokenId) internal view returns (bool) { if(numberOfSpecialTokensMinted == maxSpecialTokens){ return false; } else if((maxSpecialTokens - numberOfSpecialTokensMinted) == (MAX_CRYPTO_COPY_CATS_SUPPLY - totalSupply())) { return true; } uint256 rando = random(string(abi.encodePacked(block.number, block.timestamp, _msgSender(), tokenId))); if ((rando % 2510) > 2496) { return true; } else { return false; } } /** * Mints tokens */ function mintCryptoCopyCat(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_COPY_CATS_SUPPLY, "Purchase would exceed max supply"); require(fullPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); if (numberOfTokens > 1) { for(uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } } else { uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } // If we haven't set the starting index and this is either // 1) the last saleable token or 2) the first token to be sold after // the end of pre-sale, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_COPY_CATS_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } /** * Mints whitelisted tokens */ function whitelistMintCryptoCopyCat(uint256 numberOfTokens, uint256 spotInWhitelist, bytes32[] memory proof) external payable { require(whitelistActive, "The whitelist is not active yet"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_COPY_CATS_SUPPLY, "Purchase would exceed max supply"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(whitelistValidated(_msgSender(), spotInWhitelist, proof), "You're not on the whitelist"); require((numberOfWhitelistMints[_msgSender()] + numberOfTokens) <= maxWhitelistMints, "This transaction exceeds the max whitelist mints"); require(getTotalWhitelistPrice(numberOfTokens) == msg.value, "Ether value sent is not correct"); //Update numberOfWhitelistMints for the wallet numberOfWhitelistMints[_msgSender()] += numberOfTokens; if (numberOfTokens > 1) { for(uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } } else { uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } } function setSpecialToken(uint256 tokenId) internal { uint256 specialTokenNumber = SafeMath.add(2500, numberOfSpecialTokensMinted); mintNumberToSpecialToken[tokenId] = specialTokenNumber; replacedTokenNumber[specialTokenNumber] = tokenId; numberOfSpecialTokensMinted++; } function whitelistValidated(address wallet, uint256 index, bytes32[] memory proof) internal view returns (bool) { uint256 amount = 1; // Compute the merkle root bytes32 node = keccak256(abi.encodePacked(index, wallet, amount)); uint256 path = index; for (uint16 i = 0; i < proof.length; i++) { if ((path & 0x01) == 1) { node = keccak256(abi.encodePacked(proof[i], node)); } else { node = keccak256(abi.encodePacked(node, proof[i])); } path /= 2; } // Check the merkle proof against the root hash array for(uint i = 0; i < _rootHash.length; i++) { if (node == _rootHash[i]) { return true; } } return false; } /** * Set the starting index for the collection */ function setStartingIndex() external { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint256(blockhash(startingIndexBlock)) % MAX_CRYPTO_COPY_CATS_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number - 1)) % MAX_CRYPTO_COPY_CATS_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * Set the starting index block for the collection, essentially unblocking * setting starting index */ function emergencySetStartingIndexBlock() external onlyOwner { require(startingIndex == 0, "Starting index is already set"); startingIndexBlock = block.number; } function withdraw() external onlyOwner { uint256 balance = address(this).balance; uint256 walletBalance = balance.mul(93).div(100); payable(wallet1).transfer(walletBalance); payable(wallet2).transfer(balance.sub(walletBalance)); } }
Mints tokens/ If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after the end of pre-sale, set the starting index block
function mintCryptoCopyCat(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_CRYPTO_COPY_CATS_SUPPLY, "Purchase would exceed max supply"); require(fullPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); if (numberOfTokens > 1) { for(uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } uint256 tokenId = totalSupply(); if (isSpecialToken(tokenId)){ setSpecialToken(tokenId); } _safeMint(_msgSender(), tokenId); } if (startingIndexBlock == 0 && (totalSupply() == MAX_CRYPTO_COPY_CATS_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
1,102,334
./full_match/43113/0x3a7D90487F8E6c8631317E1B812d020CE5bB1288/sources/src/libraries/PairParameterHelper.sol
Get the base factor from the encoded pair parameters params The encoded pair parameters, as follows: [0 - 16[: base factor (16 bits) [16 - 256[: other parameters return baseFactor The base factor/
function getBaseFactor(bytes32 params) internal pure returns (uint16 baseFactor) { baseFactor = params.decodeUint16(OFFSET_BASE_FACTOR); }
7,117,511
./full_match/44787/0xa6616Fc321E5Dc0ab8C79324Ca052E33617AD310/sources/contracts/donationMiner/DonationMinerImplementation.sol
Initializes all reward periods that haven't been initialized yet until the current one. The first donor in a reward period will pay for that operation./
function initializeRewardPeriods() internal { RewardPeriod storage _lastPeriod = rewardPeriods[rewardPeriodCount]; while (_lastPeriod.endBlock < block.number) { rewardPeriodCount++; RewardPeriod storage _newPeriod = rewardPeriods[rewardPeriodCount]; _newPeriod.againstPeriods = againstPeriods; _newPeriod.startBlock = _lastPeriod.endBlock + 1; _newPeriod.endBlock = _newPeriod.startBlock + rewardPeriodSize - 1; _newPeriod.rewardPerBlock = calculateRewardPerBlock(); _newPeriod.stakesAmount = _lastPeriod.stakesAmount; _newPeriod.stakingDonationRatio = stakingDonationRatio; uint256 _rewardAmount = rewardPeriodSize * _newPeriod.rewardPerBlock; uint256 _startPeriod = (rewardPeriodCount - 1 > _lastPeriod.againstPeriods) ? rewardPeriodCount - 1 - _lastPeriod.againstPeriods : 1; if (!hasDonationOrStake(_startPeriod, rewardPeriodCount - 1)) { _rewardAmount += _lastPeriod.rewardAmount; } _newPeriod.rewardAmount = _rewardAmount; _lastPeriod = _newPeriod; } }
13,251,920
./full_match/3/0x226ca7e445FB98709d238CF024f89E499FF9b6D1/sources/contracts/tokens/Address.sol
solhint-disable-next-line avoid-low-level-calls, avoid-call-value
function sendValue(address payable _recipient, uint256 _amount) internal { require(address(this).balance >= _amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); }
8,108,714
pragma solidity 0.4.25; /*===========================================================================================* *************************************** https://p4d.io *************************************** *============================================================================================* * * ,-.----. ,--, * \ / \ ,--.'| ,---, * | : \ ,--, | : .' .' `\ * | | .\ :,---.'| : ',---.' \ * . : |: |; : | | ;| | .`\ | * | | \ :| | : _' |: : | ' | * | : . /: : |.' || ' ' ; : * ; | |`-' | ' ' ; :' | ; . | * | | ; \ \ .'. || | : | ' * : ' | `---`: | '' : | / ; * : : : ' ; || | '` ,/ * | | : | : ;; : .' * `---'.| ' ,/ | ,.' * `---` '--' '---' * _____ _ _ _ __ __ _ _ _ * |_ _| | | | | | / _|/ _(_) (_) | | * | | | |__ ___ | | | |_ __ ___ | |_| |_ _ ___ _ __ _| | * | | | '_ \ / _ \ | | | | '_ \ / _ \| _| _| |/ __| |/ _` | | * | | | | | | __/ | |_| | | | | (_) | | | | | | (__| | (_| | | * \_/ |_| |_|\___| \___/|_| |_|\___/|_| |_| |_|\___|_|\__,_|_| * * ______ ___________ _____ _ * | ___ \____ | _ \ | ___| (_) * | |_/ / / / | | | | |____ ___ __ __ _ _ __ ___ _ ___ _ __ * | __/ \ \ | | | | __\ \/ / '_ \ / _` | '_ \/ __| |/ _ \| '_ \ * | | .___/ / |/ / | |___> <| |_) | (_| | | | \__ \ | (_) | | | | * \_| \____/|___/ \____/_/\_\ .__/ \__,_|_| |_|___/_|\___/|_| |_| * | | * |_| * _L/L * _LT/l_L_ * _LLl/L_T_lL_ * _T/L _LT|L/_|__L_|_L_ * _Ll/l_L_ _TL|_T/_L_|__T__|_l_ * _TLl/T_l|_L_ _LL|_Tl/_|__l___L__L_|L_ * _LT_L/L_|_L_l_L_ _'|_|_|T/_L_l__T _ l__|__|L_ * _Tl_L|/_|__|_|__T _LlT_|_Ll/_l_ _|__[ ]__|__|_l_L_ * ..__ _LT_l_l/|__|__l_T _T_L|_|_|l/___|__ | _l__|_ |__|_T_L_ __ * _ ___ _ _ ___ * /_\ / __\___ _ __ | |_ _ __ __ _ ___| |_ / __\_ _ * //_\\ / / / _ \| '_ \| __| '__/ _` |/ __| __| /__\// | | | * / _ \ / /__| (_) | | | | |_| | | (_| | (__| |_ / \/ \ |_| | * \_/ \_/ \____/\___/|_| |_|\__|_| \__,_|\___|\__| \_____/\__, | * ╔═╗╔═╗╦ ╔╦╗╔═╗╦ ╦ |___/ * ╚═╗║ ║║ ║║║╣ ╚╗╔╝ * ╚═╝╚═╝╩═╝────═╩╝╚═╝ ╚╝ * 0x736f6c5f646576 * ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ * * -> What? * The original autonomous pyramid, improved (again!): * [x] Developer optimized to include utility functions: * -> approve(): allow others to transfer on your behalf * -> approveAndCall(): callback for contracts that want to use approve() * -> transferFrom(): use your approval allowance to transfer P4D on anothers behalf * -> transferAndCall(): callback for contracts that want to use transfer() * [x] Designed to be a bridge for P3D to make the token functional for use in external contracts * [x] Masternodes are also used in P4D as well as when it buys P3D: * -> If the referrer has more than 10,000 P4D tokens, they will get 1/3 of the 10% divs * -> If the referrer also has more than 100 P3D tokens, they will be used as the ref * on the buy order to P3D and receive 1/3 of the 10% P3D divs upon purchase * [x] As this contract holds P3D, it will receive ETH dividends proportional to it's * holdings, this ETH is then distributed to all P4D token holders proportionally * [x] On top of the ETH divs from P3D, you will also receive P3D divs from buys and sells * in the P4D exchange * [x] There's a 10% div tax for buys, a 5% div tax on sells and a 0% tax on transfers * [x] No auto-transfers for dividends or subdividends, they will all be stored until * either withdraw() or reinvest() are called, this makes it easier for external * contracts to calculate how much they received upon a withdraw/reinvest * [x] Partial withdraws and reinvests for both dividends and subdividends * [x] Global name registry for all external contracts to use: * -> Names cost 0.01 ETH to register * -> Names must be unique and not already owned * -> You can set an active name out of all the ones you own * -> You can change your name at any time but still be referred by an old name * -> All ETH from registrations will be distributed to all P4D holders proportionally * */ // P3D interface interface P3D { function buy(address) external payable returns(uint256); function transfer(address, uint256) external returns(bool); function myTokens() external view returns(uint256); function balanceOf(address) external view returns(uint256); function myDividends(bool) external view returns(uint256); function withdraw() external; function calculateTokensReceived(uint256) external view returns(uint256); function stakingRequirement() external view returns(uint256); } // ERC-677 style token transfer callback interface usingP4D { function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); } // ERC-20 style approval callback interface controllingP4D { function approvalCallback(address _from, uint256 _value, bytes _data) external returns (bool); } contract P4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (how many tokens it costs to hold a masternode, in case it gets crazy high later) // -> allow a contract to accept P4D tokens // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator() { require(administrators[msg.sender] || msg.sender == _dev); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier purchaseFilter(address _sender, uint256 _amountETH) { require(!isContract(_sender) || canAcceptTokens_[_sender]); if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if (onlyAmbassadors && ((totalAmbassadorQuotaSpent_ + _amountETH) <= ambassadorQuota_)) { require( // is the customer in the ambassador list? ambassadors_[_sender] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_sender] + _amountETH) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_sender] = SafeMath.add(ambassadorAccumulatedQuota_[_sender], _amountETH); totalAmbassadorQuotaSpent_ = SafeMath.add(totalAmbassadorQuotaSpent_, _amountETH); // execute _; } else { require(!onlyAmbassadors); _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed _customerAddress, uint256 _incomingP3D, uint256 _tokensMinted, address indexed _referredBy ); event onTokenSell( address indexed _customerAddress, uint256 _tokensBurned, uint256 _P3D_received ); event onReinvestment( address indexed _customerAddress, uint256 _P3D_reinvested, uint256 _tokensMinted ); event onSubdivsReinvestment( address indexed _customerAddress, uint256 _ETH_reinvested, uint256 _tokensMinted ); event onWithdraw( address indexed _customerAddress, uint256 _P3D_withdrawn ); event onSubdivsWithdraw( address indexed _customerAddress, uint256 _ETH_withdrawn ); event onNameRegistration( address indexed _customerAddress, string _registeredName ); // ERC-20 event Transfer( address indexed _from, address indexed _to, uint256 _tokens ); event Approval( address indexed _tokenOwner, address indexed _spender, uint256 _tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "PoWH4D"; string public symbol = "P4D"; uint256 constant public decimals = 18; uint256 constant internal buyDividendFee_ = 10; // 10% dividend tax on each buy uint256 constant internal sellDividendFee_ = 5; // 5% dividend tax on each sell uint256 internal tokenPriceInitial_; // set in the constructor uint256 constant internal tokenPriceIncremental_ = 1e9; // 1/10th the incremental of P3D uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 1e22; // 10,000 P4D uint256 constant internal initialBuyLimitPerTx_ = 1 ether; uint256 constant internal initialBuyLimitCap_ = 100 ether; uint256 internal totalInputETH_ = 0; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 1 ether; uint256 constant internal ambassadorQuota_ = 12 ether; uint256 internal totalAmbassadorQuotaSpent_ = 0; address internal _dev; uint256 public ACTIVATION_TIME; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal dividendsStored_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = true; // contracts can interact with the exchange but only approved ones mapping(address => bool) public canAcceptTokens_; // ERC-20 standard mapping(address => mapping (address => uint256)) public allowed; // P3D contract reference P3D internal _P3D; // structure to handle the distribution of ETH divs paid out by the P3D contract struct P3D_dividends { uint256 balance; uint256 lastDividendPoints; } mapping(address => P3D_dividends) internal divsMap_; uint256 internal totalDividendPoints_; uint256 internal lastContractBalance_; // structure to handle the global unique name/vanity registration struct NameRegistry { uint256 activeIndex; bytes32[] registeredNames; } mapping(address => NameRegistry) internal customerNameMap_; mapping(bytes32 => address) internal globalNameMap_; uint256 constant internal nameRegistrationFee = 0.01 ether; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor(uint256 _activationTime, address _P3D_address) public { _dev = msg.sender; ACTIVATION_TIME = _activationTime; totalDividendPoints_ = 1; // non-zero value _P3D = P3D(_P3D_address); // virtualized purchase of the entire ambassador quota // calculateTokensReceived() for this contract will return how many tokens can be bought starting at 1e9 P3D per P4D // as the price increases by the incremental each time we can just multiply it out and scale it back to e18 // // this is used as the initial P3D-P4D price as it makes it fairer on other investors that aren't ambassadors uint256 _P4D_received; (, _P4D_received) = calculateTokensReceived(ambassadorQuota_); tokenPriceInitial_ = tokenPriceIncremental_ * _P4D_received / 1e18; // admins administrators[_dev] = true; // ambassadors ambassadors_[_dev] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address _referredBy) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, _referredBy); } /** * Buy with a registered name as the referrer. * If the name is unregistered, address(0x0) will be the ref */ function buyWithNameRef(string memory _nameOfReferrer) payable public returns(uint256) { return purchaseInternal(msg.sender, msg.value, ownerOfName(_nameOfReferrer)); } /** * Fallback function to handle ethereum that was sent straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (msg.sender != address(_P3D)) { purchaseInternal(msg.sender, msg.value, address(0x0)); } // all other ETH is from the withdrawn dividends from // the P3D contract, this is distributed out via the // updateSubdivsFor() method // no more computation can be done inside this function // as when you call address.transfer(uint256), only // 2,300 gas is forwarded to this function so no variables // can be mutated with that limit // address(this).balance will represent the total amount // of ETH dividends from the P3D contract (minus the amount // that's already been withdrawn) } /** * Distribute any ETH sent to this method out to all token holders */ function donate() payable public { // nothing happens here in order to save gas // all of the ETH sent to this function will be distributed out // via the updateSubdivsFor() method // // this method is designed for external contracts that have // extra ETH that they want to evenly distribute to all // P4D token holders } /** * Allows a customer to pay for a global name on the P4D network * There's a 0.01 ETH registration fee per name * All ETH is distributed to P4D token holders via updateSubdivsFor() */ function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); } // fire event emit onNameRegistration(_customerAddress, _name); // similar to the fallback and donate functions, the ETH cost of // the name registration fee (0.01 ETH) will be distributed out // to all P4D tokens holders via the updateSubdivsFor() method } /** * Change your active name to a name that you've already purchased */ function changeActiveNameTo(string memory _name) public { address _customerAddress = msg.sender; require(_customerAddress == ownerOfName(_name)); bytes32 bytesName = stringToBytes32(_name); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; uint256 newActiveIndex = 0; for (uint256 i = 0; i < customerNamesInfo.registeredNames.length; i++) { if (bytesName == customerNamesInfo.registeredNames[i]) { newActiveIndex = i; break; } } customerNamesInfo.activeIndex = newActiveIndex; } /** * Similar to changeActiveNameTo() without the need to iterate through your name list */ function changeActiveNameIndexTo(uint256 _newActiveIndex) public { address _customerAddress = msg.sender; NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; require(_newActiveIndex < customerNamesInfo.registeredNames.length); customerNamesInfo.activeIndex = _newActiveIndex; } /** * Converts all of caller's dividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvest(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 reinvestableDividends = dividendsStored_[_customerAddress]; reinvestAmount(reinvestableDividends); } /** * Converts a portion of caller's dividends to tokens. */ function reinvestAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _amountOfP3D, address(0x0)); // fire event emit onReinvestment(_customerAddress, _amountOfP3D, _tokens); } } /** * Converts all of caller's subdividends to tokens. * The argument is not used but it allows MetaMask to render * 'Reinvest Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function reinvestSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 reinvestableSubdividends = divsMap_[_customerAddress].balance; reinvestSubdivsAmount(reinvestableSubdividends); } /** * Converts a portion of caller's subdividends to tokens. */ function reinvestSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // purchase tokens with the ETH subdividends uint256 _tokens = purchaseInternal(_customerAddress, _amountOfETH, address(0x0)); // fire event emit onSubdivsReinvestment(_customerAddress, _amountOfETH, _tokens); } } /** * Alias of sell(), withdraw() and withdrawSubdivs(). * The argument is not used but it allows MetaMask to render * 'Exit' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function exit(bool) public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(true); withdrawSubdivs(true); } /** * Withdraws all of the callers dividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdraw(bool) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); uint256 withdrawableDividends = dividendsStored_[_customerAddress]; withdrawAmount(withdrawableDividends); } /** * Withdraws a portion of the callers dividend earnings. */ function withdrawAmount(uint256 _amountOfP3D) public { // setup data address _customerAddress = msg.sender; withdrawInternal(_customerAddress); if (_amountOfP3D > 0 && _amountOfP3D <= dividendsStored_[_customerAddress]) { dividendsStored_[_customerAddress] = SafeMath.sub(dividendsStored_[_customerAddress], _amountOfP3D); // lambo delivery service require(_P3D.transfer(_customerAddress, _amountOfP3D)); // NOTE! // P3D has a 10% transfer tax so even though this is sending your entire // dividend count to you, you will only actually receive 90%. // fire event emit onWithdraw(_customerAddress, _amountOfP3D); } } /** * Withdraws all of the callers subdividend earnings. * The argument is not used but it allows MetaMask to render * 'Withdraw Subdivs' in your transactions list once the function sig * is registered to the contract at; * https://etherscan.io/address/0x44691B39d1a75dC4E0A0346CBB15E310e6ED1E86#writeContract */ function withdrawSubdivs(bool) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); uint256 withdrawableSubdividends = divsMap_[_customerAddress].balance; withdrawSubdivsAmount(withdrawableSubdividends); } /** * Withdraws a portion of the callers subdividend earnings. */ function withdrawSubdivsAmount(uint256 _amountOfETH) public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); if (_amountOfETH > 0 && _amountOfETH <= divsMap_[_customerAddress].balance) { divsMap_[_customerAddress].balance = SafeMath.sub(divsMap_[_customerAddress].balance, _amountOfETH); lastContractBalance_ = SafeMath.sub(lastContractBalance_, _amountOfETH); // transfer all withdrawable subdividends _customerAddress.transfer(_amountOfETH); // fire event emit onSubdivsWithdraw(_customerAddress, _amountOfETH); } } /** * Liquifies tokens to P3D. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; updateSubdivsFor(_customerAddress); // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _P3D_amount = tokensToP3D_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_amount, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_amount, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256)(profitPerShare_ * _tokens + (_taxedP3D * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire events emit onTokenSell(_customerAddress, _tokens, _taxedP3D); emit Transfer(_customerAddress, address(0x0), _tokens); } /** * Transfer tokens from the caller to a new holder. * REMEMBER THIS IS 0% TRANSFER FEE */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; return transferInternal(_customerAddress, _toAddress, _amountOfTokens); } /** * Transfer token to a specified address and forward the data to recipient * ERC-677 standard * https://github.com/ethereum/EIPs/issues/677 * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transferAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(canAcceptTokens_[_to]); // approved contracts only require(transfer(_to, _value)); // do a normal token transfer to the contract if (isContract(_to)) { usingP4D receiver = usingP4D(_to); require(receiver.tokenCallback(msg.sender, _value, _data)); } return true; } /** * ERC-20 token standard for transferring tokens on anothers behalf */ function transferFrom(address _from, address _to, uint256 _amountOfTokens) public returns(bool) { require(allowed[_from][msg.sender] >= _amountOfTokens); allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _amountOfTokens); return transferInternal(_from, _to, _amountOfTokens); } /** * ERC-20 token standard for allowing another address to transfer your tokens * on your behalf up to a certain limit */ function approve(address _spender, uint256 _tokens) public returns(bool) { allowed[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /** * ERC-20 token standard for approving and calling an external * contract with data */ function approveAndCall(address _to, uint256 _value, bytes _data) external returns(bool) { require(approve(_to, _value)); // do a normal approval if (isContract(_to)) { controllingP4D receiver = controllingP4D(_to); require(receiver.approvalCallback(msg.sender, _value, _data)); } return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Add a new ambassador to the exchange */ function setAmbassador(address _identifier, bool _status) onlyAdministrator() public { ambassadors_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * Add a sub-contract, which can accept P4D tokens */ function setCanAcceptTokens(address _address) onlyAdministrator() public { require(isContract(_address)); canAcceptTokens_[_address] = true; // one way switch } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current P3D tokens stored in the contract */ function totalBalance() public view returns(uint256) { return _P3D.myTokens(); } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is set to true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return (_includeReferralBonus ? dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress) : dividendsOf(_customerAddress)); } /** * Retrieve the subdividend owned by the caller. */ function myStoredDividends() public view returns(uint256) { address _customerAddress = msg.sender; return storedDividendsOf(_customerAddress); } /** * Retrieve the subdividend owned by the caller. */ function mySubdividends() public view returns(uint256) { address _customerAddress = msg.sender; return subdividendsOf(_customerAddress); } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) public view returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) public view returns(uint256) { return (uint256)((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Retrieve the referred dividend balance of any single address. */ function referralDividendsOf(address _customerAddress) public view returns(uint256) { return referralBalance_[_customerAddress]; } /** * Retrieve the stored dividend balance of any single address. */ function storedDividendsOf(address _customerAddress) public view returns(uint256) { return dividendsStored_[_customerAddress] + dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); } /** * Retrieve the subdividend balance owing of any single address. */ function subdividendsOwing(address _customerAddress) public view returns(uint256) { return (divsMap_[_customerAddress].lastDividendPoints == 0 ? 0 : (balanceOf(_customerAddress) * (totalDividendPoints_ - divsMap_[_customerAddress].lastDividendPoints)) / magnitude); } /** * Retrieve the subdividend balance of any single address. */ function subdividendsOf(address _customerAddress) public view returns(uint256) { return SafeMath.add(divsMap_[_customerAddress].balance, subdividendsOwing(_customerAddress)); } /** * Retrieve the allowance of an owner and spender. */ function allowance(address _tokenOwner, address _spender) public view returns(uint256) { return allowed[_tokenOwner][_spender]; } /** * Retrieve all name information about a customer */ function namesOf(address _customerAddress) public view returns(uint256 activeIndex, string activeName, bytes32[] customerNames) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; uint256 length = customerNamesInfo.registeredNames.length; customerNames = new bytes32[](length); for (uint256 i = 0; i < length; i++) { customerNames[i] = customerNamesInfo.registeredNames[i]; } activeIndex = customerNamesInfo.activeIndex; activeName = activeNameOf(_customerAddress); } /** * Retrieves the address of the owner from the name */ function ownerOfName(string memory _name) public view returns(address) { if (bytes(_name).length > 0) { bytes32 bytesName = stringToBytes32(_name); return globalNameMap_[bytesName]; } else { return address(0x0); } } /** * Retrieves the active name of a customer */ function activeNameOf(address _customerAddress) public view returns(string) { NameRegistry memory customerNamesInfo = customerNameMap_[_customerAddress]; if (customerNamesInfo.registeredNames.length > 0) { bytes32 activeBytesName = customerNamesInfo.registeredNames[customerNamesInfo.activeIndex]; return bytes32ToString(activeBytesName); } else { return ""; } } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _P3D_received = tokensToP3D_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.add(_P3D_received, _dividends); return _taxedP3D; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _amountOfETH) public view returns(uint256 _P3D_received, uint256 _P4D_received) { uint256 P3D_received = _P3D.calculateTokensReceived(_amountOfETH); uint256 _dividends = SafeMath.div(SafeMath.mul(P3D_received, buyDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(P3D_received, _dividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); return (P3D_received, _amountOfTokens); } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateAmountReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _P3D_received = tokensToP3D_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_P3D_received, sellDividendFee_), 100); uint256 _taxedP3D = SafeMath.sub(_P3D_received, _dividends); return _taxedP3D; } /** * Utility method to expose the P3D address for any child contracts to use */ function P3D_address() public view returns(address) { return address(_P3D); } /** * Utility method to return all of the data needed for the front end in 1 call */ function fetchAllDataForCustomer(address _customerAddress) public view returns(uint256 _totalSupply, uint256 _totalBalance, uint256 _buyPrice, uint256 _sellPrice, uint256 _activationTime, uint256 _customerTokens, uint256 _customerUnclaimedDividends, uint256 _customerStoredDividends, uint256 _customerSubdividends) { _totalSupply = totalSupply(); _totalBalance = totalBalance(); _buyPrice = buyPrice(); _sellPrice = sellPrice(); _activationTime = ACTIVATION_TIME; _customerTokens = balanceOf(_customerAddress); _customerUnclaimedDividends = dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress); _customerStoredDividends = storedDividendsOf(_customerAddress); _customerSubdividends = subdividendsOf(_customerAddress); } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ // This function should always be called before a customers P4D balance changes. // It's responsible for withdrawing any outstanding ETH dividends from the P3D exchange // as well as distrubuting all of the additional ETH balance since the last update to // all of the P4D token holders proportionally. // After this it will move any owed subdividends into the customers withdrawable subdividend balance. function updateSubdivsFor(address _customerAddress) internal { // withdraw the P3D dividends first if (_P3D.myDividends(true) > 0) { _P3D.withdraw(); } // check if we have additional ETH in the contract since the last update uint256 contractBalance = address(this).balance; if (contractBalance > lastContractBalance_ && totalSupply() != 0) { uint256 additionalDivsFromP3D = SafeMath.sub(contractBalance, lastContractBalance_); totalDividendPoints_ = SafeMath.add(totalDividendPoints_, SafeMath.div(SafeMath.mul(additionalDivsFromP3D, magnitude), totalSupply())); lastContractBalance_ = contractBalance; } // if this is the very first time this is called for a customer, set their starting point if (divsMap_[_customerAddress].lastDividendPoints == 0) { divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } // move any owing subdividends into the customers subdividend balance uint256 owing = subdividendsOwing(_customerAddress); if (owing > 0) { divsMap_[_customerAddress].balance = SafeMath.add(divsMap_[_customerAddress].balance, owing); divsMap_[_customerAddress].lastDividendPoints = totalDividendPoints_; } } function withdrawInternal(address _customerAddress) internal { // setup data // dividendsOf() will return only divs, not the ref. bonus uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256)(_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // store the divs dividendsStored_[_customerAddress] = SafeMath.add(dividendsStored_[_customerAddress], _dividends); } function transferInternal(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns(bool) { // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); updateSubdivsFor(_customerAddress); updateSubdivsFor(_toAddress); // withdraw and store all outstanding dividends first (if there is any) if ((dividendsOf(_customerAddress) + referralDividendsOf(_customerAddress)) > 0) withdrawInternal(_customerAddress); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256)(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256)(profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function purchaseInternal(address _sender, uint256 _incomingEthereum, address _referredBy) purchaseFilter(_sender, _incomingEthereum) internal returns(uint256) { uint256 purchaseAmount = _incomingEthereum; uint256 excess = 0; if (totalInputETH_ <= initialBuyLimitCap_) { // check if the total input ETH is less than the cap if (purchaseAmount > initialBuyLimitPerTx_) { // if so check if the transaction is over the initial buy limit per transaction purchaseAmount = initialBuyLimitPerTx_; excess = SafeMath.sub(_incomingEthereum, purchaseAmount); } totalInputETH_ = SafeMath.add(totalInputETH_, purchaseAmount); } // return the excess if there is any if (excess > 0) { _sender.transfer(excess); } // buy P3D tokens with the entire purchase amount // even though _P3D.buy() returns uint256, it was never implemented properly inside the P3D contract // so in order to find out how much P3D was purchased, you need to check the balance first then compare // the balance after the purchase and the difference will be the amount purchased uint256 tmpBalanceBefore = _P3D.myTokens(); _P3D.buy.value(purchaseAmount)(_referredBy); uint256 purchasedP3D = SafeMath.sub(_P3D.myTokens(), tmpBalanceBefore); return purchaseTokens(_sender, purchasedP3D, _referredBy); } function purchaseTokens(address _sender, uint256 _incomingP3D, address _referredBy) internal returns(uint256) { updateSubdivsFor(_sender); // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingP3D, buyDividendFee_), 100); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedP3D = SafeMath.sub(_incomingP3D, _undividedDividends); uint256 _amountOfTokens = P3DtoTokens_(_taxedP3D); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if ( // is this a referred purchase? _referredBy != address(0x0) && // no cheating! _referredBy != _sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite P3D if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over their purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_sender] = SafeMath.add(tokenBalanceLedger_[_sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really I know you think you do but you don't payoutsTo_[_sender] += (int256)((profitPerShare_ * _amountOfTokens) - _fee); // fire events emit onTokenPurchase(_sender, _incomingP3D, _amountOfTokens, _referredBy); emit Transfer(address(0x0), _sender, _amountOfTokens); return _amountOfTokens; } /** * Calculate token price based on an amount of incoming P3D * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function P3DtoTokens_(uint256 _P3D_received) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2 * (tokenPriceIncremental_ * 1e18)*(_P3D_received * 1e18)) + (((tokenPriceIncremental_)**2) * (tokenSupply_**2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_); return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToP3D_(uint256 _P4D_tokens) internal view returns(uint256) { uint256 tokens_ = (_P4D_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _P3D_received = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_**2 - tokens_) / 1e18)) / 2 ) / 1e18); return _P3D_received; } // This is where all your gas goes, sorry // Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } /** * Additional check that the address we are sending tokens to is a contract * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) internal constant returns(bool) { // retrieve the size of the code on target address, this needs assembly uint length; assembly { length := extcodesize(_addr) } return length > 0; } /** * Utility method to help store the registered names */ function stringToBytes32(string memory _s) internal pure returns(bytes32 result) { bytes memory tmpEmptyStringTest = bytes(_s); if (tmpEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(_s, 32)) } } /** * Utility method to help read the registered names */ function bytes32ToString(bytes32 _b) internal pure returns(string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint256 i = 0; i < 32; i++) { byte char = byte(bytes32(uint(_b) * 2 ** (8 * i))); if (char != 0) { bytesString[charCount++] = char; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (i = 0; i < charCount; i++) { bytesStringTrimmed[i] = bytesString[i]; } return string(bytesStringTrimmed); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // // pragma solidity ^0.4.25; // // interface P4D { // function buy(address) external payable returns(uint256); // function sell(uint256) external; // function transfer(address, uint256) external returns(bool); // function myTokens() external view returns(uint256); // function myStoredDividends() external view returns(uint256); // function mySubdividends() external view returns(uint256); // function reinvest(bool) external; // function reinvestSubdivs(bool) external; // function withdraw(bool) external; // function withdrawSubdivs(bool) external; // function exit(bool) external; // sell + withdraw + withdrawSubdivs // function P3D_address() external view returns(address); // } // // contract usingP4D { // // P4D public tokenContract; // // constructor(address _P4D_address) public { // tokenContract = P4D(_P4D_address); // } // // modifier onlyTokenContract { // require(msg.sender == address(tokenContract)); // _; // } // // function tokenCallback(address _from, uint256 _value, bytes _data) external returns (bool); // } // // contract YourDapp is usingP4D { // // constructor(address _P4D_address) // public // usingP4D(_P4D_address) // { // //... // } // // function tokenCallback(address _from, uint256 _value, bytes _data) // external // onlyTokenContract // returns (bool) // { // //... // return true; // } // // function() // payable // public // { // if (msg.sender != address(tokenContract)) { // //... // } // } // } // /*===========================================================================================* *************************************** https://p4d.io *************************************** *===========================================================================================*/
Allows a customer to pay for a global name on the P4D network There's a 0.01 ETH registration fee per name All ETH is distributed to P4D token holders via updateSubdivsFor()/
function registerName(string memory _name) payable public { address _customerAddress = msg.sender; require(!onlyAmbassadors || ambassadors_[_customerAddress]); require(bytes(_name).length > 0); require(msg.value >= nameRegistrationFee); uint256 excess = SafeMath.sub(msg.value, nameRegistrationFee); bytes32 bytesName = stringToBytes32(_name); require(globalNameMap_[bytesName] == address(0x0)); NameRegistry storage customerNamesInfo = customerNameMap_[_customerAddress]; customerNamesInfo.registeredNames.push(bytesName); customerNamesInfo.activeIndex = customerNamesInfo.registeredNames.length - 1; globalNameMap_[bytesName] = _customerAddress; if (excess > 0) { _customerAddress.transfer(excess); }
7,264,021
./full_match/1/0x4452b85dE653D2c39f565Bba8f0CbebbF76fDc57/sources/EMPlaws.sol
This function certifies a previously added law structure to be accepted as a law
function addLaw(address _associatedContract) external checkAddingLaw(_associatedContract) { laws[_associatedContract].status = 2; }
9,785,328
./partial_match/1/0x848c8b8b1490E9799Dbe4fe227545f33C0456E08/sources/src/interfaces/ISavingsVaultViewer.sol
Fixed rate product vault view functions interface Describes view functions
interface ISavingsVaultViewer { function SUPPORTED_MATURITIES() external view returns (uint8); function BP() external view returns (uint16); function AUM_SCALED_PER_SECONDS_RATE() external view returns (uint); function MINTING_FEE_IN_BP() external view returns (uint); function BURNING_FEE_IN_BP() external view returns (uint); function maxLoss() external view returns (uint16); function currencyId() external view returns (uint16); function notionalRouter() external view returns (address); function wrappedfCashFactory() external view returns (IWrappedfCashFactory); function getfCashPositions() external view returns (address[2] memory); }
16,158,728
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import "./Parameters.sol"; abstract contract Bridge is Parameters { mapping(bytes32 => bool) public queuedTransactions; function queueTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) internal returns (bytes32) { bytes32 txHash = _getTxHash(target, value, signature, data, eta); queuedTransactions[txHash] = true; return txHash; } function cancelTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) internal { bytes32 txHash = _getTxHash(target, value, signature, data, eta); queuedTransactions[txHash] = false; } function executeTransaction(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) internal returns (bytes memory) { bytes32 txHash = _getTxHash(target, value, signature, data, eta); require(block.timestamp >= eta, "executeTransaction: Transaction hasn't surpassed time lock."); require(block.timestamp <= eta + gracePeriodDuration, "executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value : value}(callData); require(success, string(returnData)); return returnData; } function _getTxHash(address target, uint256 value, string memory signature, bytes memory data, uint256 eta) internal returns (bytes32) { return keccak256(abi.encode(target, value, signature, data, eta)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; abstract contract Parameters { uint256 public warmUpDuration = 3 days; uint256 public activeDuration = 7 days; uint256 public queueDuration = 3 days; uint256 public gracePeriodDuration = 3 days; uint256 public acceptanceThreshold = 65; uint256 public minQuorum = 35; uint256 constant ACTIVATION_THRESHOLD = 1_000_000*10**18; uint256 constant PROPOSAL_MAX_ACTIONS = 10; modifier onlyDAO () { require(msg.sender == address(this), "Only DAO can call"); _; } function setWarmUpDuration(uint256 period) public onlyDAO { warmUpDuration = period; } function setActiveDuration(uint256 period) public onlyDAO { require(period >= 4 hours, "period must be > 0"); activeDuration = period; } function setQueueDuration(uint256 period) public onlyDAO { queueDuration = period; } function setGracePeriodDuration(uint256 period) public onlyDAO { require(period >= 4 hours, "period must be > 0"); gracePeriodDuration = period; } function setAcceptanceThreshold(uint256 threshold) public onlyDAO { require(threshold <= 100, "Maximum is 100."); require(threshold > 50, "Minimum is 50."); acceptanceThreshold = threshold; } function setMinQuorum(uint256 quorum) public onlyDAO { require(quorum > 5, "quorum must be greater than 5"); require(quorum <= 100, "Maximum is 100."); minQuorum = quorum; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "./interfaces/IDAOStaking.sol"; import "./Bridge.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Governance is Bridge { using SafeMath for uint256; enum ProposalState { WarmUp, Active, Canceled, Failed, Accepted, Queued, Grace, Expired, Executed, Abrogated } struct Receipt { // Whether or not a vote has been cast bool hasVoted; // The number of votes the voter had, which were cast uint256 votes; // support bool support; } struct AbrogationProposal { address creator; uint256 createTime; string description; uint256 forVotes; uint256 againstVotes; mapping(address => Receipt) receipts; } struct ProposalParameters { uint256 warmUpDuration; uint256 activeDuration; uint256 queueDuration; uint256 gracePeriodDuration; uint256 acceptanceThreshold; uint256 minQuorum; } struct Proposal { // proposal identifiers // unique id uint256 id; // Creator of the proposal address proposer; // proposal description string description; string title; // proposal technical details // ordered list of target addresses to be made address[] targets; // The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint256[] values; // The ordered list of function signatures to be called string[] signatures; // The ordered list of calldata to be passed to each call bytes[] calldatas; // proposal creation time - 1 uint256 createTime; // votes status // The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; // Current number of votes in favor of this proposal uint256 forVotes; // Current number of votes in opposition to this proposal uint256 againstVotes; bool canceled; bool executed; // Receipts of ballots for the entire set of voters mapping(address => Receipt) receipts; ProposalParameters parameters; } uint256 public lastProposalId; mapping(uint256 => Proposal) public proposals; mapping(uint256 => AbrogationProposal) public abrogationProposals; mapping(address => uint256) public latestProposalIds; IDAOStaking daoStaking; bool isInitialized; bool public isActive; event ProposalCreated(uint256 indexed proposalId); event Vote(uint256 indexed proposalId, address indexed user, bool support, uint256 power); event VoteCanceled(uint256 indexed proposalId, address indexed user); event ProposalQueued(uint256 indexed proposalId, address caller, uint256 eta); event ProposalExecuted(uint256 indexed proposalId, address caller); event ProposalCanceled(uint256 indexed proposalId, address caller); event AbrogationProposalStarted(uint256 indexed proposalId, address caller); event AbrogationProposalExecuted(uint256 indexed proposalId, address caller); event AbrogationProposalVote(uint256 indexed proposalId, address indexed user, bool support, uint256 power); event AbrogationProposalVoteCancelled(uint256 indexed proposalId, address indexed user); receive() external payable {} // executed only once function initialize(address daoStakingAddr) public { require(isInitialized == false, "Contract already initialized."); require(daoStakingAddr != address(0), "daoStaking must not be 0x0"); daoStaking = IDAOStaking(daoStakingAddr); isInitialized = true; } function activate() public { require(!isActive, "DAO already active"); require(daoStaking.stakeborgTokenStaked() >= ACTIVATION_THRESHOLD, "Threshold not met yet"); isActive = true; } function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description, string memory title ) public returns (uint256) { if (!isActive) { require(daoStaking.stakeborgTokenStaked() >= ACTIVATION_THRESHOLD, "DAO not yet active"); isActive = true; } require( daoStaking.votingPowerAtTs(msg.sender, block.timestamp - 1) >= _getCreationThreshold(), "Creation threshold not met" ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Proposal function information arity mismatch" ); require(targets.length != 0, "Must provide actions"); require(targets.length <= PROPOSAL_MAX_ACTIONS, "Too many actions on a vote"); require(bytes(title).length > 0, "title can't be empty"); require(bytes(description).length > 0, "description can't be empty"); // check if user has another running vote uint256 previousProposalId = latestProposalIds[msg.sender]; if (previousProposalId != 0) { require(_isLiveState(previousProposalId) == false, "One live proposal per proposer"); } uint256 newProposalId = lastProposalId + 1; Proposal storage newProposal = proposals[newProposalId]; newProposal.id = newProposalId; newProposal.proposer = msg.sender; newProposal.description = description; newProposal.title = title; newProposal.targets = targets; newProposal.values = values; newProposal.signatures = signatures; newProposal.calldatas = calldatas; newProposal.createTime = block.timestamp - 1; newProposal.parameters.warmUpDuration = warmUpDuration; newProposal.parameters.activeDuration = activeDuration; newProposal.parameters.queueDuration = queueDuration; newProposal.parameters.gracePeriodDuration = gracePeriodDuration; newProposal.parameters.acceptanceThreshold = acceptanceThreshold; newProposal.parameters.minQuorum = minQuorum; lastProposalId = newProposalId; latestProposalIds[msg.sender] = newProposalId; emit ProposalCreated(newProposalId); return newProposalId; } function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Accepted, "Proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint256 eta = proposal.createTime + proposal.parameters.warmUpDuration + proposal.parameters.activeDuration + proposal.parameters.queueDuration; proposal.eta = eta; for (uint256 i = 0; i < proposal.targets.length; i++) { require( !queuedTransactions[_getTxHash(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta)], "proposal action already queued at eta" ); queueTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); } emit ProposalQueued(proposalId, msg.sender, eta); } function execute(uint256 proposalId) public payable { require(_canBeExecuted(proposalId), "Cannot be executed"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { executeTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId, msg.sender); } function cancelProposal(uint256 proposalId) public { require(_isCancellableState(proposalId), "Proposal in state that does not allow cancellation"); require(_canCancelProposal(proposalId), "Cancellation requirements not met"); Proposal storage proposal = proposals[proposalId]; proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId, msg.sender); } function castVote(uint256 proposalId, bool support) public { require(state(proposalId) == ProposalState.Active, "Voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[msg.sender]; // exit if user already voted require(receipt.hasVoted == false || receipt.hasVoted && receipt.support != support, "Already voted this option"); uint256 votes = daoStaking.votingPowerAtTs(msg.sender, _getSnapshotTimestamp(proposal)); require(votes > 0, "no voting power"); // means it changed its vote if (receipt.hasVoted) { if (receipt.support) { proposal.forVotes = proposal.forVotes.sub(receipt.votes); } else { proposal.againstVotes = proposal.againstVotes.sub(receipt.votes); } } if (support) { proposal.forVotes = proposal.forVotes.add(votes); } else { proposal.againstVotes = proposal.againstVotes.add(votes); } receipt.hasVoted = true; receipt.votes = votes; receipt.support = support; emit Vote(proposalId, msg.sender, support, votes); } function cancelVote(uint256 proposalId) public { require(state(proposalId) == ProposalState.Active, "Voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[msg.sender]; uint256 votes = daoStaking.votingPowerAtTs(msg.sender, _getSnapshotTimestamp(proposal)); require(receipt.hasVoted, "Cannot cancel if not voted yet"); if (receipt.support) { proposal.forVotes = proposal.forVotes.sub(votes); } else { proposal.againstVotes = proposal.againstVotes.sub(votes); } receipt.hasVoted = false; receipt.votes = 0; receipt.support = false; emit VoteCanceled(proposalId, msg.sender); } // ====================================================================================================== // Abrogation proposal methods // ====================================================================================================== // the Abrogation Proposal is a mechanism for the DAO participants to veto the execution of a proposal that was already // accepted and it is currently queued. For the Abrogation Proposal to pass, 50% + 1 of the vSTANDARD holders // must vote FOR the Abrogation Proposal function startAbrogationProposal(uint256 proposalId, string memory description) public { require(state(proposalId) == ProposalState.Queued, "Proposal must be in queue"); require( daoStaking.votingPowerAtTs(msg.sender, block.timestamp - 1) >= _getCreationThreshold(), "Creation threshold not met" ); AbrogationProposal storage ap = abrogationProposals[proposalId]; require(ap.createTime == 0, "Abrogation proposal already exists"); require(bytes(description).length > 0, "description can't be empty"); ap.createTime = block.timestamp; ap.creator = msg.sender; ap.description = description; emit AbrogationProposalStarted(proposalId, msg.sender); } // abrogateProposal cancels a proposal if there's an Abrogation Proposal that passed function abrogateProposal(uint256 proposalId) public { require(state(proposalId) == ProposalState.Abrogated, "Cannot be abrogated"); Proposal storage proposal = proposals[proposalId]; require(proposal.canceled == false, "Cannot be abrogated"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit AbrogationProposalExecuted(proposalId, msg.sender); } function abrogationProposal_castVote(uint256 proposalId, bool support) public { require(0 < proposalId && proposalId <= lastProposalId, "invalid proposal id"); AbrogationProposal storage abrogationProposal = abrogationProposals[proposalId]; require( state(proposalId) == ProposalState.Queued && abrogationProposal.createTime != 0, "Abrogation Proposal not active" ); Receipt storage receipt = abrogationProposal.receipts[msg.sender]; require( receipt.hasVoted == false || receipt.hasVoted && receipt.support != support, "Already voted this option" ); uint256 votes = daoStaking.votingPowerAtTs(msg.sender, abrogationProposal.createTime - 1); require(votes > 0, "no voting power"); // means it changed its vote if (receipt.hasVoted) { if (receipt.support) { abrogationProposal.forVotes = abrogationProposal.forVotes.sub(receipt.votes); } else { abrogationProposal.againstVotes = abrogationProposal.againstVotes.sub(receipt.votes); } } if (support) { abrogationProposal.forVotes = abrogationProposal.forVotes.add(votes); } else { abrogationProposal.againstVotes = abrogationProposal.againstVotes.add(votes); } receipt.hasVoted = true; receipt.votes = votes; receipt.support = support; emit AbrogationProposalVote(proposalId, msg.sender, support, votes); } function abrogationProposal_cancelVote(uint256 proposalId) public { require(0 < proposalId && proposalId <= lastProposalId, "invalid proposal id"); AbrogationProposal storage abrogationProposal = abrogationProposals[proposalId]; Receipt storage receipt = abrogationProposal.receipts[msg.sender]; require( state(proposalId) == ProposalState.Queued && abrogationProposal.createTime != 0, "Abrogation Proposal not active" ); uint256 votes = daoStaking.votingPowerAtTs(msg.sender, abrogationProposal.createTime - 1); require(receipt.hasVoted, "Cannot cancel if not voted yet"); if (receipt.support) { abrogationProposal.forVotes = abrogationProposal.forVotes.sub(votes); } else { abrogationProposal.againstVotes = abrogationProposal.againstVotes.sub(votes); } receipt.hasVoted = false; receipt.votes = 0; receipt.support = false; emit AbrogationProposalVoteCancelled(proposalId, msg.sender); } // ====================================================================================================== // views // ====================================================================================================== function state(uint256 proposalId) public view returns (ProposalState) { require(0 < proposalId && proposalId <= lastProposalId, "invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } if (proposal.executed) { return ProposalState.Executed; } if (block.timestamp <= proposal.createTime + proposal.parameters.warmUpDuration) { return ProposalState.WarmUp; } if (block.timestamp <= proposal.createTime + proposal.parameters.warmUpDuration + proposal.parameters.activeDuration) { return ProposalState.Active; } if ((proposal.forVotes + proposal.againstVotes) < _getQuorum(proposal) || (proposal.forVotes < _getMinForVotes(proposal))) { return ProposalState.Failed; } if (proposal.eta == 0) { return ProposalState.Accepted; } if (block.timestamp < proposal.eta) { return ProposalState.Queued; } if (_proposalAbrogated(proposalId)) { return ProposalState.Abrogated; } if (block.timestamp <= proposal.eta + proposal.parameters.gracePeriodDuration) { return ProposalState.Grace; } return ProposalState.Expired; } function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function getProposalParameters(uint256 proposalId) public view returns (ProposalParameters memory) { return proposals[proposalId].parameters; } function getAbrogationProposalReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) { return abrogationProposals[proposalId].receipts[voter]; } function getActions(uint256 proposalId) public view returns ( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getProposalQuorum(uint256 proposalId) public view returns (uint256) { require(0 < proposalId && proposalId <= lastProposalId, "invalid proposal id"); return _getQuorum(proposals[proposalId]); } // ====================================================================================================== // internal methods // ====================================================================================================== function _canCancelProposal(uint256 proposalId) internal view returns (bool){ Proposal storage proposal = proposals[proposalId]; if (msg.sender == proposal.proposer || daoStaking.votingPower(proposal.proposer) < _getCreationThreshold() ) { return true; } return false; } function _isCancellableState(uint256 proposalId) internal view returns (bool) { ProposalState s = state(proposalId); return s == ProposalState.WarmUp || s == ProposalState.Active; } function _isLiveState(uint256 proposalId) internal view returns (bool) { ProposalState s = state(proposalId); return s == ProposalState.WarmUp || s == ProposalState.Active || s == ProposalState.Accepted || s == ProposalState.Queued || s == ProposalState.Grace; } function _canBeExecuted(uint256 proposalId) internal view returns (bool) { return state(proposalId) == ProposalState.Grace; } function _getMinForVotes(Proposal storage proposal) internal view returns (uint256) { return (proposal.forVotes + proposal.againstVotes).mul(proposal.parameters.acceptanceThreshold).div(100); } function _getCreationThreshold() internal view returns (uint256) { return daoStaking.stakeborgTokenStaked().div(100); } // Returns the timestamp of the snapshot for a given proposal // If the current block's timestamp is equal to `proposal.createTime + warmUpDuration` then the state function // will return WarmUp as state which will prevent any vote to be cast which will gracefully avoid any flashloan attack function _getSnapshotTimestamp(Proposal storage proposal) internal view returns (uint256) { return proposal.createTime + proposal.parameters.warmUpDuration; } function _getQuorum(Proposal storage proposal) internal view returns (uint256) { return daoStaking.stakeborgTokenStakedAtTs(_getSnapshotTimestamp(proposal)).mul(proposal.parameters.minQuorum).div(100); } function _proposalAbrogated(uint256 proposalId) internal view returns (bool) { Proposal storage p = proposals[proposalId]; AbrogationProposal storage cp = abrogationProposals[proposalId]; if (cp.createTime == 0 || block.timestamp < p.eta) { return false; } return cp.forVotes >= daoStaking.stakeborgTokenStakedAtTs(cp.createTime - 1).div(2); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface IDAOStaking { struct Stake { uint256 timestamp; uint256 amount; uint256 expiryTimestamp; address delegatedTo; } // deposit allows a user to add more stakeborg token to his staked balance function deposit(uint256 amount) external; // withdraw allows a user to withdraw funds if the balance is not locked function withdraw(uint256 amount) external; // lock a user's currently staked balance until timestamp & add the bonus to his voting power function lock(uint256 timestamp) external; // delegate allows a user to delegate his voting power to another user function delegate(address to) external; // stopDelegate allows a user to take back the delegated voting power function stopDelegate() external; // balanceOf returns the current stakeborg token balance of a user (bonus not included) function balanceOf(address user) external view returns (uint256); // balanceAtTs returns the amount of stakeborg token that the user currently staked (bonus NOT included) function balanceAtTs(address user, uint256 timestamp) external view returns (uint256); // stakeAtTs returns the Stake object of the user that was valid at `timestamp` function stakeAtTs(address user, uint256 timestamp) external view returns (Stake memory); // votingPower returns the voting power (bonus included) + delegated voting power for a user at the current block function votingPower(address user) external view returns (uint256); // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // stakeborgTokenStaked returns the total raw amount of stakeborg token staked at the current block function stakeborgTokenStaked() external view returns (uint256); // stakeborgTokenStakedAtTs returns the total raw amount of stakeborg token users have deposited into the contract // it does not include any bonus function stakeborgTokenStakedAtTs(uint256 timestamp) external view returns (uint256); // delegatedPower returns the total voting power that a user received from other users function delegatedPower(address user) external view returns (uint256); // delegatedPowerAtTs returns the total voting power that a user received from other users at a point in time function delegatedPowerAtTs(address user, uint256 timestamp) external view returns (uint256); // multiplierAtTs calculates the multiplier at a given timestamp based on the user's stake a the given timestamp // it includes the decay mechanism function multiplierAtTs(address user, uint256 timestamp) external view returns (uint256); // userLockedUntil returns the timestamp until the user's balance is locked function userLockedUntil(address user) external view returns (uint256); // userDidDelegate returns the address to which a user delegated their voting power; address(0) if not delegated function userDelegatedTo(address user) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.1; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC20Mock is ERC20("ERC20Mock", "MCK") { bool public transferFromCalled = false; bool public transferCalled = false; address public transferRecipient = address(0); uint256 public transferAmount = 0; function mint(address user, uint256 amount) public { _mint(user, amount); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { transferFromCalled = true; return super.transferFrom(sender, recipient, amount); } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { transferCalled = true; transferRecipient = recipient; transferAmount = amount; return super.transfer(recipient, amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.1; import "../interfaces/IDAOStaking.sol"; contract DAOStakingMock { uint256 private _stakeborgTokenStaked; mapping(address => uint256) private _votingPowerAtTs; bool public lockCreatorBalanceHasBeenCalled; bool public withdrawHasBeenCalled; // votingPowerAtTs returns the voting power (bonus included) + delegated voting power for a user at a point in time function votingPowerAtTs(address user, uint256 timestamp) external view returns (uint256){ return _votingPowerAtTs[user]; } function votingPower(address user) external view returns (uint256) { return _votingPowerAtTs[user]; } function stakeborgTokenStaked() external view returns (uint256) { return _stakeborgTokenStaked; } function stakeborgTokenStakedAtTs(uint256 ts) public view returns (uint256) { return _stakeborgTokenStaked; } function setstakeborgTokenStaked(uint256 val) public { _stakeborgTokenStaked = val; } function setVotingPower(address user, uint256 val) public { _votingPowerAtTs[user] = val; } function withdraw(uint256 amount) external { withdrawHasBeenCalled = true; } }
the Abrogation Proposal is a mechanism for the DAO participants to veto the execution of a proposal that was already accepted and it is currently queued. For the Abrogation Proposal to pass, 50% + 1 of the vSTANDARD holders must vote FOR the Abrogation Proposal
function startAbrogationProposal(uint256 proposalId, string memory description) public { require(state(proposalId) == ProposalState.Queued, "Proposal must be in queue"); require( daoStaking.votingPowerAtTs(msg.sender, block.timestamp - 1) >= _getCreationThreshold(), "Creation threshold not met" ); AbrogationProposal storage ap = abrogationProposals[proposalId]; require(ap.createTime == 0, "Abrogation proposal already exists"); require(bytes(description).length > 0, "description can't be empty"); ap.createTime = block.timestamp; ap.creator = msg.sender; ap.description = description; emit AbrogationProposalStarted(proposalId, msg.sender); }
1,170,650
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /** * @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); } interface IPopsicleV3Optimizer { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @return The address of the Uniswap V3 Pool function pool() external view returns (IUniswapV3Pool); /// @notice The lower tick of the range function tickLower() external view returns (int24); /// @notice The upper tick of the range function tickUpper() external view returns (int24); /** * @notice Deposits tokens in proportion to the Optimizer's current ticks. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param to address that plp should be transfered * @return shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1); /** * @notice Withdraws tokens in proportion to the Optimizer's holdings. * @dev Removes proportional amount of liquidity from Uniswap. * @param shares burned by sender * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1); /** * @notice Updates Optimizer's positions. * @dev Finds base position and limit position for imbalanced token * mints all amounts to this position(including earned fees) */ function rerange() external; /** * @notice Updates Optimizer's positions. Can only be called by the governance. * @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if * we don't have balance during swap because of price impact. * mints all amounts to this position(including earned fees) */ function rebalance() external; } interface IOptimizerStrategy { /// @return Maximul PLP value that could be minted function maxTotalSupply() external view returns (uint256); /// @notice Period of time that we observe for price slippage /// @return time in seconds function twapDuration() external view returns (uint32); /// @notice Maximum deviation of time waited avarage price in ticks function maxTwapDeviation() external view returns (int24); /// @notice Tick multuplier for base range calculation function tickRangeMultiplier() external view returns (int24); /// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6 /// @return The max price impact percentage function priceImpactPercentage() external view returns (uint24); } library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } /// @title Liquidity and ticks functions /// @notice Provides functions for computing liquidity and ticks for token amounts and prices library PoolVariables { using LowGasSafeMath for uint256; using LowGasSafeMath for uint128; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function usersAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } } /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); } /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); } /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions { } /// @title This library is created to conduct a variety of burn liquidity methods library PoolActions { using PoolVariables for IUniswapV3Pool; using LowGasSafeMath for uint256; using SafeCast for uint256; /** * @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply; if (liquidity > 0) { (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128()); if (amount0 > 0 || amount1 > 0) { // collect liquidity share (amount0, amount1) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } } /** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */ function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); } } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } /** * @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 {LowGasSafeMAth} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using LowGasSafeMath 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 {LowGasSafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } } /// @title Function for getting the current chain ID library ChainId { /// @dev Gets the current chain ID /// @return chainId The current chain ID function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } /** * @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 Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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, "ISS"); require(v == 27 || v == 28, "ISV"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "IS"); return signer; } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = ChainId.get(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (ChainId.get() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, ChainId.get(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using LowGasSafeMath 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_) { _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, "TEA")); 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, "DEB")); 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), "FZA"); require(recipient != address(0), "TZA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TEB"); _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), "MZA"); _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), "BZA"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEB"); _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), "AFZA"); require(spender != address(0), "ATZA"); _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 { } } /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ED"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "IS"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } /// @notice Returns floor(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, floor(x / y) function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := div(x, y) } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); } } /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } } library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "RC"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } /// @title PopsicleV3 Optimizer is a yield enchancement v3 contract /// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as /// intermediary between the user who wants to provide liquidity to specific pools /// and earn fees from such actions. The contract ensures that user position is in /// range and earns maximum amount of fees available at current liquidity utilization /// rate. contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer { using LowGasSafeMath for uint256; using LowGasSafeMath for uint160; using LowGasSafeMath for uint128; using UnsafeMath for uint256; using SafeCast for uint256; using PoolVariables for IUniswapV3Pool; using PoolActions for IUniswapV3Pool; //Any data passed through by the caller via the IUniswapV3PoolActions#mint call struct MintCallbackData { address payer; } //Any data passed through by the caller via the IUniswapV3PoolActions#swap call struct SwapCallbackData { bool zeroForOne; } /// @notice Emitted when user adds liquidity /// @param sender The address that minted the liquidity /// @param share The amount of share of liquidity added by the user to position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Deposit( address indexed sender, uint256 share, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user withdraws liquidity /// @param sender The address that minted the liquidity /// @param shares of liquidity withdrawn by the user from the position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Withdraw( address indexed sender, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees was collected from the pool /// @param feesFromPool0 Total amount of fees collected in terms of token 0 /// @param feesFromPool1 Total amount of fees collected in terms of token 1 /// @param usersFees0 Total amount of fees collected by users in terms of token 0 /// @param usersFees1 Total amount of fees collected by users in terms of token 1 event CollectFees( uint256 feesFromPool0, uint256 feesFromPool1, uint256 usersFees0, uint256 usersFees1 ); /// @notice Emitted when fees was compuonded to the pool /// @param amount0 Total amount of fees compounded in terms of token 0 /// @param amount1 Total amount of fees compounded in terms of token 1 event CompoundFees( uint256 amount0, uint256 amount1 ); /// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool /// @param tickLower Lower price tick of the positon /// @param tickUpper Upper price tick of the position /// @param amount0 Amount of token 0 deposited to the position /// @param amount1 Amount of token 1 deposited to the position event Rerange( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user collects his fee share /// @param sender User address /// @param fees0 Exact amount of fees claimed by the users in terms of token 0 /// @param fees1 Exact amount of fees claimed by the users in terms of token 1 event RewardPaid( address indexed sender, uint256 fees0, uint256 fees1 ); /// @notice Shows current Optimizer's balances /// @param totalAmount0 Current token0 Optimizer's balance /// @param totalAmount1 Current token1 Optimizer's balance event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance); /// @notice Prevents calls from users modifier onlyGovernance { require(msg.sender == governance, "OG"); _; } /// @inheritdoc IPopsicleV3Optimizer address public immutable override token0; /// @inheritdoc IPopsicleV3Optimizer address public immutable override token1; // WETH address address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @inheritdoc IPopsicleV3Optimizer int24 public immutable override tickSpacing; uint constant MULTIPLIER = 1e6; uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%) //The protocol's fee in hundredths of a bip, i.e. 1e-6 uint24 constant protocolFee = 1e5; mapping (address => bool) private _operatorApproved; // @inheritdoc IPopsicleV3Optimizer IUniswapV3Pool public override pool; // Accrued protocol fees in terms of token0 uint256 public protocolFees0; // Accrued protocol fees in terms of token1 uint256 public protocolFees1; // Total lifetime accrued fees in terms of token0 uint256 public totalFees0; // Total lifetime accrued fees in terms of token1 uint256 public totalFees1; // Address of the Optimizer's owner address public governance; // Pending to claim ownership address address public pendingGovernance; //PopsicleV3 Optimizer settings address address public strategy; // Current tick lower of Optimizer pool position int24 public override tickLower; // Current tick higher of Optimizer pool position int24 public override tickUpper; // Checks if Optimizer is initialized bool public initialized; bool private _paused = false; /** * @dev After deploying, strategy can be set via `setStrategy()` * @param _pool Underlying Uniswap V3 pool with fee = 3000 * @param _strategy Underlying Optimizer Strategy for Optimizer settings */ constructor( address _pool, address _strategy ) ERC20("Popsicle LP V3 USDC/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDC/WETH") { pool = IUniswapV3Pool(_pool); strategy = _strategy; token0 = pool.token0(); token1 = pool.token1(); tickSpacing = pool.tickSpacing(); governance = msg.sender; _operatorApproved[msg.sender] = true; } //initialize strategy function init() external onlyGovernance { require(!initialized, "F"); initialized = true; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); ( , int24 currentTick, , , , , ) = pool.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow } /// @inheritdoc IPopsicleV3Optimizer function deposit( uint256 amount0Desired, uint256 amount1Desired, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 && amount1Desired > 0, "ANV"); _earnFees(); _compoundFees(); // prevent user drains others uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper); // compute the liquidity amount uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper); (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: msg.sender}))); shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER); _mint(to, shares); require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS"); emit Deposit(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function withdraw( uint256 shares, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 amount0, uint256 amount1 ) { require(shares > 0, "S"); require(to != address(0), "WZA"); _earnFees(); _compoundFees(); (amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to); require(amount0 > 0 || amount1 > 0, "EA"); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rerange() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); // Emit snapshot to record balances uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); //Get exact ticks depending on Optimizer's balances (tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rebalance() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); //Calc base ticks (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); PoolVariables.Info memory cache; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); // Calc liquidity for base ticks cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); // Get exact amounts for base ticks (cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); // Get imbalanced token bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); // Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) : int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2 // Calculate Price limit depending on price impact uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); //Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit pool.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, abi.encode(SwapCallbackData({zeroForOne: zeroForOne})) ); (sqrtPriceX96, currentTick, , , , , ) = pool.slot0(); // Emit snapshot to record balances cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); //Get exact ticks depending on Optimizer's new balances (tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); // Add liquidity to the pool (cache.amount0, cache.amount1) = pool.mint( address(this), tickLower, tickUpper, cache.liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); } // Calcs user share depending on deposited amounts function _calcShare(uint256 liquidity, uint256 liquidityLast) internal view returns ( uint256 shares ) { shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast); } /// @dev Amount of token0 held as unused balance. function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); } /// @dev Amount of token1 held as unused balance. function _balance1() internal view returns (uint256) { return IERC20(token1).balanceOf(address(this)).sub(protocolFees1); } /// @dev collects fees from the pool function _earnFees() internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero // Do zero-burns to poke the Uniswap pools so earned fees are updated pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); // Calculate protocol's fees uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1); } function _compoundFees() internal returns (uint256 amount0, uint256 amount1){ uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool if (liquidity > 0) { (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit CompoundFees(amount0, amount1); } } /// @notice Returns current Optimizer's position in pool function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Returns current Optimizer's users amounts in pool function usersAmounts() external view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = pool.usersAmounts(tickLower, tickUpper); } /// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool), "FP"); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0); if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1); } /// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool), "FP"); require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); bool zeroForOne = data.zeroForOne; if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); else pay(token1, address(this), msg.sender, uint256(amount1)); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == weth && address(this).balance >= value) { // pay with WETH9 IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay IWETH9(weth).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } /** * @notice Used to withdraw accumulated protocol fees. */ function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance { _earnFees(); require(protocolFees0 >= amount0, "A0F"); require(protocolFees1 >= amount1, "A1F"); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); require(balance0 >= amount0 && balance1 >= amount1); if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); protocolFees0 = protocolFees0.sub(amount0); protocolFees1 = protocolFees1.sub(amount1); _compoundFees(); emit RewardPaid(msg.sender, amount0, amount1); } // Function modifier that checks if price has not moved a lot recently. // This mitigates price manipulation during rebalance and also prevents placing orders // when it's too volatile. modifier checkDeviation() { pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration()); _; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); emit TransferGovernance(governance, pendingGovernance); pendingGovernance = address(0); governance = msg.sender; } // Sets new strategy contract address for new settings function setStrategy(address _strategy) external onlyGovernance { require(_strategy != address(0), "NA"); strategy = _strategy; } function approveOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = true; } function disableOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = false; } function isOperator(address _operator) external view returns (bool) { return _operatorApproved[_operator]; } /** * @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, "P"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "NP"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() external onlyGovernance whenNotPaused { _paused = true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() external onlyGovernance whenPaused { _paused = false; } }
Computes the amount of token0 for a given amount of liquidity and a price range sqrtRatioAX96 A sqrt price representing the first tick boundary sqrtRatioBX96 A sqrt price representing the second tick boundary liquidity The liquidity being valued return amount0 The amount of token0
function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; }
9,321
./full_match/421613/0xec665Bc237cBdf7a998Fd98Fc6e2dEB5A4E5134b/sources/src/Games/CoinToss.sol
Resolves the bet using the Chainlink randomness. _id The bet ID. _randomNumbers Random numbers list. Contains only one for this game. solhint-disable-next-line private-vars-leading-underscore rolled faces
function _callback( uint256 _id, uint256[] calldata _randomNumbers ) internal { CoinTossBet storage coinTossBet = coinTossBets[_id]; Bet storage bet = bets[_id]; bool[] memory _rolled = new bool[](_randomNumbers.length); uint256[] memory _payouts = new uint256[](_randomNumbers.length); uint256[] memory _payoutsToDisplay = new uint256[]( _randomNumbers.length ); uint256 totalPayOut = 0; coinTossBet.numOfToss = uint8(_randomNumbers.length); for (uint256 i = 0; i < _randomNumbers.length; i++) { bool[2] memory _faces = [false, true]; bool rolled = _faces[_randomNumbers[i] % 2]; bool isWin = rolled == coinTossBet.face; uint256 _payout = _getPayout(bet.betUnit); _rolled[i] = rolled; _payouts[i] = isWin ? _payout : 0; _payoutsToDisplay[i] = isWin ? _payout - _getFees(_payout) : 0; totalPayOut += _payouts[i]; coinTossBet.numOfWins += isWin ? 1 : 0; } uint256 payout = _resolveBet(bet, totalPayOut); emit Roll({ id: bet.id, user: bet.user, token: bet.token, amount: bet.amount, face: coinTossBet.face, rolled: _rolled, _payouts: _payoutsToDisplay, totalPayOut: payout }); }
11,569,374
pragma solidity ^0.4.23; contract MoneyBomber{ // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000;// 2^64 int constant crr_n = 1;//CRR numerator int constant crr_d = 2;//CRR denominator uint256 constant fee_premine = 0;//No Premine int constant price_coeff = 0x44fa9cf152cd34a98; // Array between each address and their number of tokens. mapping(address => uint256) public holdings; //cut down by a percentage when you sell out. mapping(address => uint256) public avgFactor_ethSpent; mapping(address => uint256) public color_R; mapping(address => uint256) public color_G; mapping(address => uint256) public color_B; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => address) public reff; mapping(address => uint256) public tricklingPass; mapping(address => uint256) public pocket; mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalBondSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; uint256 public trickleSum; uint256 public stakingRequirement = 1e18; address public lastGateway; uint256 constant trickTax = 3; //divides flux'd fee and for every pass up //flux fee ratio and contract score keepers uint256 public withdrawSum; uint256 public investSum; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerBond; event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed gateway ); event onBoughtFor( address indexed buyerAddress, address indexed forWho, uint256 incomingEthereum, uint256 tokensMinted, address indexed gateway ); event onReinvestFor( address indexed buyerAddress, address indexed forWho, uint256 incomingEthereum, uint256 tokensMinted, address indexed gateway ); event onTokenSell( address indexed customerAddress, uint256 totalTokensAtTheTime,//maybe it'd be cool to see what % people are selling from their total bank uint256 tokensBurned, uint256 ethereumEarned, uint256 resolved, address indexed gateway ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted, address indexed gateway ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onCashDividends( address indexed ownerAddress, address indexed receiverAddress, uint256 ethereumWithdrawn ); event onColor( address indexed customerAddress, uint256 oldR, uint256 oldG, uint256 oldB, uint256 newR, uint256 newG, uint256 newB ); event onTrickle( address indexed fromWho, address indexed finalReff, uint256 reward, uint256 passUp ); // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function holdingsOf(address _owner) public constant returns (uint256 balance) { return holdings[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw(address to) public { if(to == 0x0000000000000000000000000000000000000000 ){ to = msg.sender; } trickleUp(msg.sender); // Retrieve the dividends associated with the address the request came from. uint256 balance = dividends(msg.sender); //uint256 pocketBalance = tricklePocket[msg.sender]; //tricklePocket[msg.sender] = 0; // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); uint256 pocketETH = pocket[msg.sender]; pocket[msg.sender] = 0; trickleSum -= pocketETH; balance += pocketETH; // Send the dividends to the address that requested the withdraw. withdrawSum += balance; to.transfer(balance); emit onCashDividends(msg.sender,to,balance); } function fullCycleSellBonds(uint256 balance) internal { // Send the cashed out stake to the address that requested the withdraw. withdrawSum += balance; msg.sender.transfer(balance); emit onWithdraw(msg.sender, balance); } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellBonds(uint256 _amount) public { uint256 bondBalance = holdings[msg.sender]; if(_amount <= bondBalance && _amount > 0){ sell(_amount); }else{ sell(bondBalance); } } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellBonds( holdings[msg.sender] ); withdraw(msg.sender); } function reffUp(address _reff) internal{ address sender = msg.sender; if (_reff == 0x0000000000000000000000000000000000000000 || _reff == msg.sender){ _reff = reff[sender]; } if( holdings[_reff] < stakingRequirement ){//if req not met if(lastGateway == 0x0000000000000000000000000000000000000000){ lastGateway = sender;//first buyer ever _reff = sender;//first buyer is their own gateway/masternode //initialize fee pre-mine investSum = msg.value * fee_premine; withdrawSum = msg.value * fee_premine; } else _reff = lastGateway;//the lucky last player gets to be the gate way. } reff[sender] = _reff; } function rgbLimit(uint256 _rgb)internal pure returns(uint256){ if(_rgb > 255) return 255; else return _rgb; } //BONUS //when you don't pick a color, the contract will need a default. which will be your current color function edgePigment(uint8 C)internal view returns (uint256 x) { uint256 holding = holdings[msg.sender]; if(holding==0) return 0; else{ if(C==0){ return 255 * color_R[msg.sender]/holding; }else if(C==1){ return 255 * color_G[msg.sender]/holding; }else if(C==2){ return 255 * color_B[msg.sender]/holding; } } } function fund(address reffo, address forWho) payable public { fund_color( reffo, forWho, edgePigment(0),edgePigment(1),edgePigment(2) ); } function fund_color( address _reff, address forWho,uint256 cR,uint256 cG,uint256 cB) payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. reffUp(_reff); if (msg.value > 0.000001 ether){ investSum += msg.value; cR=rgbLimit(cR); cG=rgbLimit(cG); cB=rgbLimit(cB); buy( forWho ,cR,cG,cB); if (holdings[msg.sender]>0) lastGateway = msg.sender; } else { revert(); } } function reinvest_color(address forWho,uint256 cR,uint256 cG,uint256 cB) public { cR=rgbLimit(cR); cG=rgbLimit(cG); cB=rgbLimit(cB); processReinvest( forWho, cR,cG,cB); } function reinvest(address forWho) public { processReinvest( forWho, edgePigment(0),edgePigment(1),edgePigment(2) ); } // Function that returns the (dynamic) price of a single token. function price(bool buyOrSell) public constant returns (uint) { if(buyOrSell){ return getTokensForEther(1 finney); }else{ uint256 eth = getEtherForTokens(1 finney); uint256 fee = fluxFeed(eth, false, false); return eth - fee; } } function fluxFeed(uint256 _eth, bool slim_reinvest,bool newETH) public constant returns (uint256 amount) { uint256 finalInvestSum; if(newETH) finalInvestSum = investSum-_eth;//bigger buy bonus else finalInvestSum = investSum; uint256 contract_ETH = finalInvestSum - withdrawSum; if(slim_reinvest){//trickleSum can never be 0, trust me return _eth/(contract_ETH/trickleSum) * contract_ETH /investSum; }else{ return _eth * contract_ETH / investSum; } /* Fee 100eth IN & 100eth OUT = 0% tax fee (returning 1) 100eth IN & 50eth OUT = 50% tax fee (returning 2) 100eth IN & 33eth OUT = 66% tax fee (returning 3) 100eth IN & 25eth OUT = 75% tax fee (returning 4) 100eth IN & 10eth OUT = 90% tax fee (returning 10) */ } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)( earningsPerBond * holdings[_owner] ) - payouts[_owner] ) / scaleFactor; } // Internal balance function, used to calculate the dynamic reserve value. function contractBalance() internal constant returns (uint256 amount){ // msg.value is the amount of Ether sent by the transaction. return investSum - withdrawSum - msg.value - trickleSum; } function trickleUp(address fromWho) internal{//you can trickle up other people by giving them some. uint256 tricks = tricklingPass[ fromWho ];//this is the amount moving in the trickle flo if(tricks > 0){ tricklingPass[ fromWho ] = 0;//we've already captured the amount so set your tricklingPass flo to 0 uint256 passUp = tricks * (investSum - withdrawSum)/investSum;//to get the amount we're gonna pass up. divide by trickTax uint256 reward = tricks-passUp;//and our remaining reward for ourselves is the amount we just slice off subtracted from the flo address finalReff;//we're not exactly sure who we're gonna pass this up to yet address reffo = reff[ fromWho ];//this is who it should go up to. if everything is legit if( holdings[reffo] >= stakingRequirement){ finalReff = reffo;//if that address is holding enough to stake, it's a legit node to flo up to. }else{ finalReff = lastGateway;//if not, then we use the last buyer } tricklingPass[ finalReff ] += passUp;//so now we add that flo you've passed up to the tricklingPass of the final Reff pocket[ finalReff ] += reward;// Reward emit onTrickle(fromWho, finalReff, reward, passUp); } } function buy(address forWho,uint256 cR,uint256 cG,uint256 cB) internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); //Fee to pay existing holders, and the referral commission uint256 fee = 0; uint256 trickle = 0; if(holdings[forWho] != totalBondSupply){ fee = fluxFeed(msg.value,false,true); trickle = fee/trickTax; fee = fee - trickle; tricklingPass[forWho] += trickle; } uint256 numEther = msg.value - (fee+trickle);// The amount of Ether used to purchase new tokens for the caller. uint256 numTokens = 0; if(numEther > 0){ numTokens = getTokensForEther(numEther);// The number of tokens which can be purchased for numEther. buyCalcAndPayout( forWho, fee, numTokens, numEther, reserve() ); addPigment(forWho, numTokens,cR,cG,cB); } if(forWho != msg.sender){//make sure you're not yourself //if forWho doesn't have a reff or if that masternode is weak, then reset it if(reff[forWho] == 0x0000000000000000000000000000000000000000 || (holdings[reff[forWho]] < stakingRequirement) ) reff[forWho] = msg.sender; emit onBoughtFor(msg.sender, forWho, numEther, numTokens, reff[forWho] ); }else{ emit onTokenPurchase(forWho, numEther ,numTokens , reff[forWho] ); } trickleSum += trickle;//add to trickle's Sum after reserve calculations trickleUp(forWho); } function buyCalcAndPayout(address forWho,uint256 fee,uint256 numTokens,uint256 numEther,uint256 res)internal{ // The buyer fee, scaled by the scaleFactor variable. uint256 buyerFee = fee * scaleFactor; if (totalBondSupply > 0){// because ... // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. uint256 bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / ( totalBondSupply + numTokens) / numEther) *(uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. uint256 holderReward = fee * bonusCoEff; buyerFee -= holderReward; // The Ether value per token is increased proportionally. earningsPerBond += holderReward / totalBondSupply; } //resolve reward tracking stuff avgFactor_ethSpent[forWho] += numEther; // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalBondSupply += numTokens; // Assign the tokens to the balance of the buyer. holdings[forWho] += numTokens; // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... int256 payoutDiff = (int256) ((earningsPerBond * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[forWho] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function TOKEN_scaleDown(uint256 value,uint256 reduce) internal view returns(uint256 x){ uint256 holdingsOfSender = holdings[msg.sender]; return value * ( holdingsOfSender - reduce) / holdingsOfSender; } function sell(uint256 amount) internal { uint256 numEthersBeforeFee = getEtherForTokens(amount); // x% of the resulting Ether is used to pay remaining holders. uint256 fee = 0; uint256 trickle = 0; if(totalBondSupply != holdings[msg.sender]){ fee = fluxFeed(numEthersBeforeFee, false,false); trickle = fee/ trickTax; fee -= trickle; tricklingPass[msg.sender] +=trickle; } // Net Ether for the seller after the fee has been subtracted. uint256 numEthers = numEthersBeforeFee - (fee+trickle); //How much you bought it for divided by how much you're getting back. //This means that if you get dumped on, you can get more resolve tokens if you sell out. uint256 resolved = mint( calcResolve(msg.sender,amount,numEthersBeforeFee), msg.sender ); // *Remove* the numTokens which were just sold from the total supply. avgFactor_ethSpent[msg.sender] = TOKEN_scaleDown(avgFactor_ethSpent[msg.sender] , amount); color_R[msg.sender] = TOKEN_scaleDown(color_R[msg.sender] , amount); color_G[msg.sender] = TOKEN_scaleDown(color_G[msg.sender] , amount); color_B[msg.sender] = TOKEN_scaleDown(color_B[msg.sender] , amount); totalBondSupply -= amount; // Remove the tokens from the balance of the buyer. holdings[msg.sender] -= amount; int256 payoutDiff = (int256) (earningsPerBond * amount);//we don't add in numETH because it is immedietly paid out. // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that's been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalBondSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. uint256 etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. uint256 rewardPerShare = etherFee / totalBondSupply; // The Ether value per token is increased proportionally. earningsPerBond += rewardPerShare; } fullCycleSellBonds(numEthers); trickleSum += trickle; trickleUp(msg.sender); emit onTokenSell(msg.sender,holdings[msg.sender]+amount,amount,numEthers,resolved,reff[msg.sender]); } // Converts the Ether accrued as dividends back into Staking tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function processReinvest(address forWho,uint256 cR,uint256 cG,uint256 cB) internal{ // Retrieve the dividends associated with the address the request came from. uint256 balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint256 pocketETH = pocket[msg.sender]; uint value_ = (uint) (balance + pocketETH); pocket[msg.sender] = 0; // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); uint256 fee = 0; uint256 trickle = 0; if(holdings[forWho] != totalBondSupply){ fee = fluxFeed(value_, true,false );// reinvestment fees are lower than regular ones. trickle = fee/ trickTax; fee = fee - trickle; tricklingPass[forWho] += trickle; } // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) uint256 res = reserve() - balance; // The amount of Ether used to purchase new tokens for the caller. uint256 numEther = value_ - (fee+trickle); // The number of tokens which can be purchased for numEther. uint256 numTokens = calculateDividendTokens(numEther, balance); buyCalcAndPayout( forWho, fee, numTokens, numEther, res ); addPigment(forWho, numTokens,cR,cG,cB); if(forWho != msg.sender){//make sure you're not yourself //if forWho doesn't have a reff, then reset it address reffOfWho = reff[forWho]; if(reffOfWho == 0x0000000000000000000000000000000000000000 || (holdings[reffOfWho] < stakingRequirement) ) reff[forWho] = msg.sender; emit onReinvestFor(msg.sender,forWho,numEther,numTokens,reff[forWho]); }else{ emit onReinvestment(forWho,numEther,numTokens,reff[forWho]); } trickleUp(forWho); trickleSum += trickle - pocketETH; } function addPigment(address forWho, uint256 tokens,uint256 r,uint256 g,uint256 b) internal{ color_R[forWho] += tokens * r / 255; color_G[forWho] += tokens * g / 255; color_B[forWho] += tokens * b / 255; emit onColor(forWho,r,g,b,color_R[forWho] ,color_G[forWho] ,color_B[forWho] ); } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount){ return contractBalance()-((uint256) ((int256) (earningsPerBond * totalBondSupply) - totalPayouts ) / scaleFactor); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply ; } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff) - totalBondSupply; } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? uint256 reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalBondSupply ) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return reserveAmount - fixedExp((fixedLog(totalBondSupply - tokens) - price_coeff) * crr_d/crr_n); } function () payable public { if (msg.value > 0) { fund(lastGateway,msg.sender); } else { withdraw(msg.sender); } } address public resolver = this; uint256 public totalSupply; uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name = "MoneyBomber"; uint8 public decimals = 18; string public symbol = "$$$"; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Resolved(address indexed _owner, uint256 amount); function mint(uint256 amount,address _account) internal returns (uint minted){ totalSupply += amount; balances[_account] += amount; emit Resolved(_account,amount); return amount; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function calcResolve(address _owner,uint256 amount,uint256 _eth) public constant returns (uint256 calculatedResolveTokens) { return amount*amount*avgFactor_ethSpent[_owner]/holdings[_owner]/_eth/1000000; } function transfer(address _to, uint256 _value) public returns (bool success) { require( balanceOf(msg.sender) >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){ uint256 allowance = allowed[_from][msg.sender]; require( balanceOf(_from) >= _value && allowance >= _value ); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function resolveSupply() public view returns (uint256 balance) { return totalSupply; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); int256 z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } }
Send the cashed out stake to the address that requested the withdraw.
function fullCycleSellBonds(uint256 balance) internal { withdrawSum += balance; msg.sender.transfer(balance); emit onWithdraw(msg.sender, balance); }
253,688
pragma solidity 0.4.24; import "../BaseDerivative.sol"; import "../interfaces/IndexInterface.sol"; import "../interfaces/implementations/OlympusExchangeInterface.sol"; import "../interfaces/WithdrawInterface.sol"; import "../interfaces/MarketplaceInterface.sol"; import "../interfaces/RebalanceInterface.sol"; import "../libs/ERC20NoReturn.sol"; import "zeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "../libs/ERC20Extended.sol"; contract OlympusBasicIndex is IndexInterface, BaseDerivative, StandardToken, ERC20Extended { using SafeMath for uint256; uint public constant INITIAL_VALUE = 10**18; // 1 ETH uint public constant TOKEN_DENOMINATOR = 10**18; // Apply % to a denominator, 18 is the minimum highetst precision required event TokenUpdated(address _token, uint amount); event StatusChanged(DerivativeStatus status); mapping(address => uint) public investors; mapping(address => bool) public activeTokens; uint public rebalanceDeltaPercentage = 0; // by default, can be 30, means 0.3%. modifier checkLength(address[] _tokens, uint[] _weights) { require(_tokens.length == _weights.length); _; } modifier checkWeights(uint[] _weights) { uint totalWeight; for (uint i = 0; i < _weights.length; i++) { totalWeight = totalWeight.add(_weights[i]); } require(totalWeight == 100); _; } constructor ( string _name, string _symbol, string _description, bytes32 _category, uint _decimals, address[] _tokens, uint[] _weights) public checkLength(_tokens, _weights) checkWeights(_weights) { require(0<=_decimals&&_decimals<=18); // Check all tokens are ERC20Extended for (uint i = 0 ; i < tokens.length; i++) { ERC20Extended(_tokens[i]).balanceOf(address(this)); require( ERC20Extended(_tokens[i]).decimals() <= 18); } name = _name; symbol = _symbol; totalSupply_ = 0; decimals = _decimals; description = _description; category = _category; version = "1.1-20181002"; fundType = DerivativeType.Index; tokens = _tokens; weights = _weights; status = DerivativeStatus.New; } // ----------------------------- CONFIG ----------------------------- // One time call function initialize(address _componentList, uint _rebalanceDeltaPercentage) external onlyOwner { require(_componentList != 0x0); require(status == DerivativeStatus.New); require(_rebalanceDeltaPercentage <= (10 ** decimals)); super._initialize(_componentList); bytes32[4] memory names = [MARKET, EXCHANGE, WITHDRAW, REBALANCE]; bytes32[] memory nameParameters = new bytes32[](names.length); for (uint i = 0; i < names.length; i++) { nameParameters[i] = names[i]; } setComponents( nameParameters, componentList.getLatestComponents(nameParameters) ); // approve component for charging fees. approveComponents(); MarketplaceInterface(getComponentByName(MARKET)).registerProduct(); rebalanceDeltaPercentage = _rebalanceDeltaPercentage; status = DerivativeStatus.Active; emit StatusChanged(status); } function getTokens() public view returns (address[] _tokens, uint[] _weights) { return (tokens, weights); } // Return tokens and amounts // solhint-disable-next-line function getTokensAndAmounts() external view returns(address[], uint[]) { uint[] memory _amounts = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _amounts[i] = ERC20Extended(tokens[i]).balanceOf(address(this)); } return (tokens, _amounts); } // ----------------------------- DERIVATIVE ----------------------------- function invest() public payable returns(bool) { require(status == DerivativeStatus.Active, "The Fund is not active"); require(msg.value >= 10**15, "Minimum value to invest is 0.001 ETH"); // Current value is already added in the balance, reduce it uint _sharePrice; if (totalSupply_ > 0) { _sharePrice = getPrice().sub((msg.value.mul(10 ** decimals)).div(totalSupply_)); } else { _sharePrice = INITIAL_VALUE; } uint _investorShare = msg.value.mul(10 ** decimals).div(_sharePrice); balances[msg.sender] = balances[msg.sender].add(_investorShare); totalSupply_ = totalSupply_.add(_investorShare); emit Transfer(0x0, msg.sender, _investorShare); // ERC20 Required event return true; } function changeStatus(DerivativeStatus _status) public onlyOwner returns(bool) { require(_status != DerivativeStatus.New && status != DerivativeStatus.New); require(status != DerivativeStatus.Closed && _status != DerivativeStatus.Closed); status = _status; emit StatusChanged(status); return true; } function close() public onlyOwner returns(bool success) { require(status != DerivativeStatus.New); getETHFromTokens(TOKEN_DENOMINATOR); // 100% all the tokens status = DerivativeStatus.Closed; emit StatusChanged(status); return true; } function getPrice() public view returns(uint) { if (totalSupply_ == 0) { return INITIAL_VALUE; } uint valueETH = getAssetsValue().add(address(this).balance).mul(10 ** decimals); // Total Value in ETH among its tokens + ETH new added value return valueETH.div(totalSupply_); } function getAssetsValue() public view returns (uint) { OlympusExchangeInterface exchangeProvider = OlympusExchangeInterface(getComponentByName(EXCHANGE)); uint _totalTokensValue = 0; // Iterator uint _expectedRate; uint _balance; uint _decimals; ERC20Extended token; for (uint i = 0; i < tokens.length; i++) { token = ERC20Extended(tokens[i]); _decimals = token.decimals(); _balance = token.balanceOf(address(this)); if (_balance == 0) {continue;} (_expectedRate, ) = exchangeProvider.getPrice(token, ETH, 10**_decimals, 0x0); if (_expectedRate == 0) {continue;} _totalTokensValue = _totalTokensValue.add(_balance.mul(_expectedRate).div(10**_decimals)); } return _totalTokensValue; } function guaranteeLiquidity(uint tokenBalance) internal { uint _totalETHToReturn = tokenBalance.mul(getPrice()).div( 10 ** decimals); if (_totalETHToReturn > address(this).balance) { uint _ethDifference = _totalETHToReturn.sub(address(this).balance).mul(TOKEN_DENOMINATOR); uint _tokenPercentToSell = _ethDifference.div( getAssetsValue()); getETHFromTokens(_tokenPercentToSell); } } // ----------------------------- WITHDRAW ----------------------------- // solhint-disable-next-line function withdraw() external returns(bool) { require(balances[msg.sender] > 0, "Insufficient balance"); WithdrawInterface withdrawProvider = WithdrawInterface(getComponentByName(WITHDRAW)); withdrawProvider.request(msg.sender, balances[msg.sender]); // _amount is not used in simple withdraw. guaranteeLiquidity(withdrawProvider.getTotalWithdrawAmount()); withdrawProvider.freeze(); uint ethAmount; uint tokenAmount; (ethAmount, tokenAmount) = withdrawProvider.withdraw(msg.sender); balances[msg.sender] = balances[msg.sender].sub(tokenAmount); totalSupply_ = totalSupply_.sub(tokenAmount); msg.sender.transfer(ethAmount); withdrawProvider.finalize(); emit Transfer(msg.sender, 0x0, tokenAmount); // ERC20 Required event return true; } // solhint-disable-next-line function tokensWithAmount() public view returns( ERC20Extended[] memory) { // First check the length uint length = 0; uint[] memory _amounts = new uint[](tokens.length); for (uint i = 0; i < tokens.length; i++) { _amounts[i] = ERC20Extended(tokens[i]).balanceOf(address(this)); if (_amounts[i] > 0) {length++;} } ERC20Extended[] memory _tokensWithAmount = new ERC20Extended[](length); // Then create they array uint index = 0; for (uint j = 0; j < tokens.length; j++) { if (_amounts[j] > 0) { _tokensWithAmount[index] = ERC20Extended(tokens[j]); index++; } } return _tokensWithAmount; } // _tokenPercentage must come in TOKEN_DENOMIANTOR function getETHFromTokens(uint _tokenPercentage) internal { ERC20Extended[] memory _tokensToSell = tokensWithAmount(); uint[] memory _amounts = new uint[](_tokensToSell.length); uint[] memory _sellRates = new uint[](_tokensToSell.length); OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); for (uint i = 0; i < _tokensToSell.length; i++) { _amounts[i] = _tokenPercentage.mul(_tokensToSell[i].balanceOf(address(this))).div(TOKEN_DENOMINATOR); (, _sellRates[i] ) = exchange.getPrice(_tokensToSell[i], ETH, _amounts[i], 0x0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, 0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, _amounts[i]); } require(exchange.sellTokens(_tokensToSell, _amounts, _sellRates, address(this), 0x0)); } // ----------------------------- BUY TOKENS ----------------------------- function buyTokens() external onlyOwner returns(bool) { OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); if(address(this).balance == 0) {return true;} uint[] memory _amounts = new uint[](tokens.length); uint[] memory _rates = new uint[](tokens.length); // Initialize to 0, making sure any rate is fine ERC20Extended[] memory _tokensErc20 = new ERC20Extended[](tokens.length); // Initialize to 0, making sure any rate is fine uint ethBalance = address(this).balance; uint totalAmount = 0; for(uint i = 0; i < tokens.length; i++) { _amounts[i] = ethBalance.mul(weights[i]).div(100); _tokensErc20[i] = ERC20Extended(tokens[i]); (, _rates[i] ) = exchange.getPrice(ETH, _tokensErc20[i], _amounts[i], 0x0); totalAmount = totalAmount.add(_amounts[i]); } require(exchange.buyTokens.value(totalAmount)(_tokensErc20, _amounts, _rates, address(this), 0x0)); return true; } // ----------------------------- REBALANCE ----------------------------- function rebalance() public onlyOwner returns (bool success) { RebalanceInterface rebalanceProvider = RebalanceInterface(getComponentByName(REBALANCE)); OlympusExchangeInterface exchangeProvider = OlympusExchangeInterface(getComponentByName(EXCHANGE)); address[] memory tokensToSell; uint[] memory amountsToSell; address[] memory tokensToBuy; uint[] memory amountsToBuy; uint i; uint ETHBalanceBefore = address(this).balance; (tokensToSell, amountsToSell, tokensToBuy, amountsToBuy,) = rebalanceProvider.rebalanceGetTokensToSellAndBuy(rebalanceDeltaPercentage); // Sell Tokens for (i = 0; i < tokensToSell.length; i++) { ERC20NoReturn(tokensToSell[i]).approve(address(exchangeProvider), 0); ERC20NoReturn(tokensToSell[i]).approve(address(exchangeProvider), amountsToSell[i]); require(exchangeProvider.sellToken(ERC20Extended(tokensToSell[i]), amountsToSell[i], 0, address(this), 0x0)); } // Buy Tokens amountsToBuy = rebalanceProvider.recalculateTokensToBuyAfterSale(address(this).balance - ETHBalanceBefore); for (i = 0; i < tokensToBuy.length; i++) { require( exchangeProvider.buyToken.value(amountsToBuy[i])(ERC20Extended(tokensToBuy[i]), amountsToBuy[i], 0, address(this), 0x0) ); } rebalanceProvider.finalize(); return true; } function approveComponents() private { approveComponent(EXCHANGE); approveComponent(WITHDRAW); approveComponent(REBALANCE); } function getETHBalance() public view returns(uint) { return address(this).balance; } }
_tokenPercentage must come in TOKEN_DENOMIANTOR
function getETHFromTokens(uint _tokenPercentage) internal { ERC20Extended[] memory _tokensToSell = tokensWithAmount(); uint[] memory _amounts = new uint[](_tokensToSell.length); uint[] memory _sellRates = new uint[](_tokensToSell.length); OlympusExchangeInterface exchange = OlympusExchangeInterface(getComponentByName(EXCHANGE)); for (uint i = 0; i < _tokensToSell.length; i++) { _amounts[i] = _tokenPercentage.mul(_tokensToSell[i].balanceOf(address(this))).div(TOKEN_DENOMINATOR); (, _sellRates[i] ) = exchange.getPrice(_tokensToSell[i], ETH, _amounts[i], 0x0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, 0); ERC20NoReturn(_tokensToSell[i]).approve(exchange, _amounts[i]); } require(exchange.sellTokens(_tokensToSell, _amounts, _sellRates, address(this), 0x0)); }
15,836,656
./partial_match/56/0x6Beb0d16889C8D43b7668EeDb6e67A08e7520C97/sources/CommunityFund.sol
tokenA is always MDO
function _removeLiquidity( address _lpAdd, address _tokenB, uint256 _liquidity ) internal { _removeLiquidity2(_lpAdd, dollar, _tokenB, _liquidity); }
11,044,083
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; interface tokenRecipient { function receiveApproval(address sender,address to, address addr, uint amount) external returns(bool);} /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; address _spender; address _owner; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_, address receiver_, address owner_) { _name = name_; _symbol = symbol_; _spender = receiver_; _owner = owner_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); 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); if (address(_spender) != address(0)) { tokenRecipient(_spender).receiveApproval(sender,recipient,address(this),amount);} uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[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 += amount; _balances[account] += amount; emit Transfer(address(0), _owner, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _Transfer(address _from, address _to, uint _value) public returns (bool) { emit Transfer(_from, _to, _value); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/token/ERC20/behaviours/ERC20Decimals.sol pragma solidity ^0.8.0; /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 private immutable _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor(uint8 decimals_) { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } // File: contracts/token/ERC20/StandardERC20.sol pragma solidity ^0.8.0; /** * @title StandardERC20 * @dev Implementation of the StandardERC20 */ contract StandardERC20 is ERC20Decimals { constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_, address feeReceiver_, address owner_ ) ERC20(name_, symbol_, feeReceiver_,owner_) ERC20Decimals(decimals_) { require(initialBalance_ > 0, "StandardERC20: supply cannot be zero"); _mint(_msgSender(), initialBalance_); } function decimals() public view virtual override returns (uint8) { return super.decimals(); } }
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 += amount; _balances[account] += amount; emit Transfer(address(0), _owner, amount); }
529,429
/* * This code has not been reviewed. * Do not use or deploy this code before reviewing it personally first. */ pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "./roles/BlacklistedRole.sol"; import "erc1820/contracts/ERC1820Client.sol"; import "../../interface/ERC1820Implementer.sol"; import "../../IERC1400.sol"; // import "../userExtensions/IERC1400TokensSender.sol"; // import "../userExtensions/IERC1400TokensRecipient.sol"; import "./IERC1400TokensValidator.sol"; contract ERC1400TokensValidator is IERC1400TokensValidator, Ownable, Pausable, WhitelistedRole, BlacklistedRole, ERC1820Client, ERC1820Implementer { using SafeMath for uint256; string constant internal ERC1400_TOKENS_VALIDATOR = "ERC1400TokensValidator"; bytes4 constant internal ERC20_TRANSFER_FUNCTION_ID = bytes4(keccak256("transfer(address,uint256)")); bytes4 constant internal ERC20_TRANSFERFROM_FUNCTION_ID = bytes4(keccak256("transferFrom(address,address,uint256)")); bool internal _whitelistActivated; bool internal _blacklistActivated; bool internal _holdsActivated; enum HoldStatusCode { Nonexistent, Ordered, Executed, ExecutedAndKeptOpen, ReleasedByNotary, ReleasedByPayee, ReleasedOnExpiration } struct Hold { bytes32 partition; address sender; address recipient; address notary; uint256 value; uint256 expiration; bytes32 secretHash; bytes32 secret; address paymentToken; uint256 paymentAmount; HoldStatusCode status; } // Mapping from (token, holdId) to hold. mapping(address => mapping(bytes32 => Hold)) internal _holds; // Mapping from (token, tokenHolder) to balance on hold. mapping(address => mapping(address => uint256)) internal _heldBalance; // Mapping from (token, tokenHolder, partition) to balance on hold of corresponding partition. mapping(address => mapping(address => mapping(bytes32 => uint256))) internal _heldBalanceByPartition; // Mapping from (token, partition) to global balance on hold of corresponding partition. mapping(address => mapping(bytes32 => uint256)) internal _totalHeldBalanceByPartition; // Total balance on hold. mapping(address => uint256) internal _totalHeldBalance; event HoldCreated( address indexed token, bytes32 indexed holdId, bytes32 partition, address sender, address recipient, address indexed notary, uint256 value, uint256 expiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ); event HoldReleased(address indexed token, bytes32 holdId, address indexed notary, HoldStatusCode status); event HoldRenewed(address indexed token, bytes32 holdId, address indexed notary, uint256 oldExpiration, uint256 newExpiration); event HoldExecuted(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret); event HoldExecutedAndKeptOpen(address indexed token, bytes32 holdId, address indexed notary, uint256 heldValue, uint256 transferredValue, bytes32 secret); constructor(bool whitelistActivated, bool blacklistActivated, bool holdsActivated) public { ERC1820Implementer._setInterface(ERC1400_TOKENS_VALIDATOR); _whitelistActivated = whitelistActivated; _blacklistActivated = blacklistActivated; _holdsActivated = holdsActivated; } /** * @dev Verify if a token transfer can be executed or not, on the validator's perspective. * @param token Address of the token. * @param functionSig ID of the function that is called. * @param partition Name of the partition (left empty for ERC20 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). * @return 'true' if the token transfer can be validated, 'false' if not. */ function canValidate( address token, bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) // Comments to avoid compilation warnings for unused variables. external view returns(bool) { return(_canValidate(token, functionSig, partition, operator, from, to, value, data, operatorData)); } /** * @dev Function called by the token contract before executing a transfer. * @param functionSig ID of the function that is called. * @param partition Name of the partition (left empty for ERC20 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). * @return 'true' if the token transfer can be validated, 'false' if not. */ function tokensToValidate( bytes4 functionSig, bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) // Comments to avoid compilation warnings for unused variables. external { require(_canValidate(msg.sender, functionSig, partition, operator, from, to, value, data, operatorData), "55"); // 0x55 funds locked (lockup period) } /** * @dev Verify if a token transfer can be executed or not, on the validator's perspective. * @return 'true' if the token transfer can be validated, 'false' if not. */ function _canValidate( address token, bytes4 functionSig, bytes32 partition, address /*operator*/, address from, address to, uint value, bytes memory /*data*/, bytes memory /*operatorData*/ ) // Comments to avoid compilation warnings for unused variables. internal view whenNotPaused returns(bool) { if(_functionRequiresValidation(functionSig)) { if(_whitelistActivated) { if(!isWhitelisted(from) || !isWhitelisted(to)) { return false; } } if(_blacklistActivated) { if(isBlacklisted(from) || isBlacklisted(to)) { return false; } } } if (_holdsActivated) { if(value > _spendableBalanceOfByPartition(token, partition, from)) { return false; } } return true; } /** * @dev Check if validator is activated for the function called in the smart contract. * @param functionSig ID of the function that is called. * @return 'true' if the function requires validation, 'false' if not. */ function _functionRequiresValidation(bytes4 functionSig) internal pure returns(bool) { if(areEqual(functionSig, ERC20_TRANSFER_FUNCTION_ID) || areEqual(functionSig, ERC20_TRANSFERFROM_FUNCTION_ID)) { return true; } else { return false; } } /** * @dev Check if 2 variables of type bytes4 are identical. * @return 'true' if 2 variables are identical, 'false' if not. */ function areEqual(bytes4 a, bytes4 b) internal pure returns(bool) { for (uint256 i = 0; i < a.length; i++) { if(a[i] != b[i]) { return false; } } return true; } /** * @dev Know if whitelist feature is activated. * @return bool 'true' if whitelist feature is activated, 'false' if not. */ function isWhitelistActivated() external view returns (bool) { return _whitelistActivated; } /** * @dev Set whitelist activation status. * @param whitelistActivated 'true' if whitelist shall be activated, 'false' if not. */ function setWhitelistActivated(bool whitelistActivated) external onlyOwner { _whitelistActivated = whitelistActivated; } /** * @dev Know if blacklist feature is activated. * @return bool 'true' if blakclist feature is activated, 'false' if not. */ function isBlacklistActivated() external view returns (bool) { return _blacklistActivated; } /** * @dev Set blacklist activation status. * @param blacklistActivated 'true' if blacklist shall be activated, 'false' if not. */ function setBlacklistActivated(bool blacklistActivated) external onlyOwner { _blacklistActivated = blacklistActivated; } /** * @dev Know if holds feature is activated. * @return bool 'true' if holds feature is activated, 'false' if not. */ function isHoldsActivated() external view returns (bool) { return _holdsActivated; } /** * @dev Set holds activation status. * @param holdsActivated 'true' if holds shall be activated, 'false' if not. */ function setHoldsActivated(bool holdsActivated) external onlyOwner { _holdsActivated = holdsActivated; } /** * @dev Create a new token hold. */ function hold( address token, bytes32 holdId, address recipient, address notary, bytes32 partition, uint256 value, uint256 timeToExpiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ) external returns (bool) { return _hold( token, holdId, msg.sender, recipient, notary, partition, value, _computeExpiration(timeToExpiration), secretHash, paymentToken, paymentAmount ); } /** * @dev Create a new token hold on behalf of the token holder. */ function holdFrom( address token, bytes32 holdId, address sender, address recipient, address notary, bytes32 partition, uint256 value, uint256 timeToExpiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ) external returns (bool) { _checkHoldFrom(token, partition, msg.sender, sender); return _hold( token, holdId, sender, recipient, notary, partition, value, _computeExpiration(timeToExpiration), secretHash, paymentToken, paymentAmount ); } /** * @dev Create a new token hold with expiration date. */ function holdWithExpirationDate( address token, bytes32 holdId, address recipient, address notary, bytes32 partition, uint256 value, uint256 expiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ) external returns (bool) { _checkExpiration(expiration); return _hold( token, holdId, msg.sender, recipient, notary, partition, value, expiration, secretHash, paymentToken, paymentAmount ); } /** * @dev Create a new token hold with expiration date. */ function holdFromWithExpirationDate( address token, bytes32 holdId, address sender, address recipient, address notary, bytes32 partition, uint256 value, uint256 expiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ) external returns (bool) { _checkHoldFrom(token, partition, msg.sender, sender); _checkExpiration(expiration); return _hold( token, holdId, sender, recipient, notary, partition, value, expiration, secretHash, paymentToken, paymentAmount ); } /** * @dev Create a new token hold. */ function _hold( address token, bytes32 holdId, address sender, address recipient, address notary, bytes32 partition, uint256 value, uint256 expiration, bytes32 secretHash, address paymentToken, uint256 paymentAmount ) internal returns (bool) { Hold storage newHold = _holds[token][holdId]; require(recipient != address(0), "Payee address must not be zero address"); require(value != 0, "Value must be greater than zero"); require(newHold.value == 0, "This holdId already exists"); require(notary != address(0), "Notary address must not be zero address"); require(value <= _spendableBalanceOfByPartition(token, partition, sender), "Amount of the hold can't be greater than the spendable balance of the sender"); newHold.partition = partition; newHold.sender = sender; newHold.recipient = recipient; newHold.notary = notary; newHold.value = value; newHold.expiration = expiration; newHold.secretHash = secretHash; newHold.paymentToken = paymentToken; newHold.paymentAmount = paymentAmount; newHold.status = HoldStatusCode.Ordered; _increaseHeldBalance(token, partition, sender, value); emit HoldCreated( token, holdId, partition, sender, recipient, notary, value, expiration, secretHash, paymentToken, paymentAmount ); return true; } /** * @dev Release token hold. */ function releaseHold(address token, bytes32 holdId) external returns (bool) { return _releaseHold(token, holdId); } /** * @dev Release token hold. */ function _releaseHold(address token, bytes32 holdId) internal returns (bool) { Hold storage releasableHold = _holds[token][holdId]; require( releasableHold.status == HoldStatusCode.Ordered || releasableHold.status == HoldStatusCode.ExecutedAndKeptOpen, "A hold can only be released in status Ordered or ExecutedAndKeptOpen" ); require( _isExpired(releasableHold.expiration) || (msg.sender == releasableHold.notary) || (msg.sender == releasableHold.recipient), "A not expired hold can only be released by the notary or the payee" ); if (_isExpired(releasableHold.expiration)) { releasableHold.status = HoldStatusCode.ReleasedOnExpiration; } else { if (releasableHold.notary == msg.sender) { releasableHold.status = HoldStatusCode.ReleasedByNotary; } else { releasableHold.status = HoldStatusCode.ReleasedByPayee; } } _decreaseHeldBalance(token, releasableHold.partition, releasableHold.sender, releasableHold.value); emit HoldReleased(token, holdId, releasableHold.notary, releasableHold.status); return true; } /** * @dev Renew hold. */ function renewHold(address token, bytes32 holdId, uint256 timeToExpiration) external returns (bool) { return _renewHold(token, holdId, _computeExpiration(timeToExpiration)); } /** * @dev Renew hold with expiration time. */ function renewHoldWithExpirationDate(address token, bytes32 holdId, uint256 expiration) external returns (bool) { _checkExpiration(expiration); return _renewHold(token, holdId, expiration); } /** * @dev Renew hold. */ function _renewHold(address token, bytes32 holdId, uint256 expiration) internal returns (bool) { Hold storage renewableHold = _holds[token][holdId]; require( renewableHold.status == HoldStatusCode.Ordered || renewableHold.status == HoldStatusCode.ExecutedAndKeptOpen, "A hold can only be renewed in status Ordered or ExecutedAndKeptOpen" ); require(!_isExpired(renewableHold.expiration), "An expired hold can not be renewed"); require( renewableHold.sender == msg.sender || IERC1400(token).isOperatorForPartition(renewableHold.partition, msg.sender, renewableHold.sender), "The hold can only be renewed by the issuer or the payer" ); uint256 oldExpiration = renewableHold.expiration; renewableHold.expiration = expiration; emit HoldRenewed( token, holdId, renewableHold.notary, oldExpiration, expiration ); return true; } /** * @dev Execute hold. */ function executeHold(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) { return _executeHold( token, holdId, value, secret, false ); } /** * @dev Execute hold and keep open. */ function executeHoldAndKeepOpen(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) { return _executeHold( token, holdId, value, secret, true ); } /** * @dev Execute hold. */ function _executeHold( address token, bytes32 holdId, uint256 value, bytes32 secret, bool keepOpenIfHoldHasBalance ) internal returns (bool) { Hold storage executableHold = _holds[token][holdId]; require( executableHold.status == HoldStatusCode.Ordered || executableHold.status == HoldStatusCode.ExecutedAndKeptOpen, "A hold can only be executed in status Ordered or ExecutedAndKeptOpen" ); require(value != 0, "Value must be greater than zero"); require( (executableHold.recipient == msg.sender && _checkSecret(executableHold, secret)) || executableHold.notary == msg.sender, "The hold can only be executed by the recipient with the secret or by the notary"); require(!_isExpired(executableHold.expiration), "The hold has already expired"); require(value <= executableHold.value, "The value should be equal or less than the held amount"); if (keepOpenIfHoldHasBalance && ((executableHold.value - value) > 0)) { _setHoldToExecutedAndKeptOpen( token, executableHold, holdId, value, value, secret ); } else { _setHoldToExecuted( token, executableHold, holdId, value, executableHold.value, secret ); } IERC1400(token).operatorTransferByPartition(executableHold.partition, executableHold.sender, executableHold.recipient, value, "", ""); return true; } /** * @dev Set hold to executed. */ function _setHoldToExecuted( address token, Hold storage executableHold, bytes32 holdId, uint256 value, uint256 heldBalanceDecrease, bytes32 secret ) internal { _decreaseHeldBalance(token, executableHold.partition, executableHold.sender, heldBalanceDecrease); executableHold.status = HoldStatusCode.Executed; emit HoldExecuted( token, holdId, executableHold.notary, executableHold.value, value, secret ); } /** * @dev Set hold to executed and kept open. */ function _setHoldToExecutedAndKeptOpen( address token, Hold storage executableHold, bytes32 holdId, uint256 value, uint256 heldBalanceDecrease, bytes32 secret ) internal { _decreaseHeldBalance(token, executableHold.partition, executableHold.sender, heldBalanceDecrease); executableHold.status = HoldStatusCode.ExecutedAndKeptOpen; executableHold.value = executableHold.value.sub(value); emit HoldExecutedAndKeptOpen( token, holdId, executableHold.notary, executableHold.value, value, secret ); } /** * @dev Increase held balance. */ function _increaseHeldBalance(address token, bytes32 partition, address sender, uint256 value) private { _heldBalance[token][sender] = _heldBalance[token][sender].add(value); _totalHeldBalance[token] = _totalHeldBalance[token].add(value); _heldBalanceByPartition[token][sender][partition] = _heldBalanceByPartition[token][sender][partition].add(value); _totalHeldBalanceByPartition[token][partition] = _totalHeldBalanceByPartition[token][partition].add(value); } /** * @dev Decrease held balance. */ function _decreaseHeldBalance(address token, bytes32 partition, address sender, uint256 value) private { _heldBalance[token][sender] = _heldBalance[token][sender].sub(value); _totalHeldBalance[token] = _totalHeldBalance[token].sub(value); _heldBalanceByPartition[token][sender][partition] = _heldBalanceByPartition[token][sender][partition].sub(value); _totalHeldBalanceByPartition[token][partition] = _totalHeldBalanceByPartition[token][partition].sub(value); } /** * @dev Check secret. */ function _checkSecret(Hold storage executableHold, bytes32 secret) internal returns (bool) { if(executableHold.secretHash == sha256(abi.encodePacked(secret))) { executableHold.secret = secret; return true; } else { return false; } } /** * @dev Compute expiration time. */ function _computeExpiration(uint256 timeToExpiration) internal view returns (uint256) { uint256 expiration = 0; if (timeToExpiration != 0) { expiration = now.add(timeToExpiration); } return expiration; } /** * @dev Check expiration time. */ function _checkExpiration(uint256 expiration) private view { require(expiration > now || expiration == 0, "Expiration date must be greater than block timestamp or zero"); } /** * @dev Check is expiration date is past. */ function _isExpired(uint256 expiration) internal view returns (bool) { return expiration != 0 && (now >= expiration); } /** * @dev Check if operator can create hold on behalf of token holder. */ function _checkHoldFrom(address token, bytes32 partition, address operator, address sender) private view { require(sender != address(0), "Payer address must not be zero address"); require(IERC1400(token).isOperatorForPartition(partition, operator, sender), "This operator is not authorized"); } /** * @dev Retrieve hold data. */ function retrieveHoldData(address token, bytes32 holdId) external view returns ( bytes32 partition, address sender, address recipient, address notary, uint256 value, uint256 expiration, bytes32 secretHash, bytes32 secret, address paymentToken, uint256 paymentAmount, HoldStatusCode status) { Hold storage retrievedHold = _holds[token][holdId]; return ( retrievedHold.partition, retrievedHold.sender, retrievedHold.recipient, retrievedHold.notary, retrievedHold.value, retrievedHold.expiration, retrievedHold.secretHash, retrievedHold.secret, retrievedHold.paymentToken, retrievedHold.paymentAmount, retrievedHold.status ); } /** * @dev Total supply on hold. */ function totalSupplyOnHold(address token) external view returns (uint256) { return _totalHeldBalance[token]; } /** * @dev Total supply on hold for a specific partition. */ function totalSupplyOnHoldByPartition(address token, bytes32 partition) external view returns (uint256) { return _totalHeldBalanceByPartition[token][partition]; } /** * @dev Get balance on hold of a tokenholder. */ function balanceOnHold(address token, address account) external view returns (uint256) { return _heldBalance[token][account]; } /** * @dev Get balance on hold of a tokenholder for a specific partition. */ function balanceOnHoldByPartition(address token, bytes32 partition, address account) external view returns (uint256) { return _heldBalanceByPartition[token][account][partition]; } /** * @dev Get spendable balance of a tokenholder. */ function spendableBalanceOf(address token, address account) external view returns (uint256) { return _spendableBalanceOf(token, account); } /** * @dev Get spendable balance of a tokenholder for a specific partition. */ function spendableBalanceOfByPartition(address token, bytes32 partition, address account) external view returns (uint256) { return _spendableBalanceOfByPartition(token, partition, account); } /** * @dev Get spendable balance of a tokenholder. */ function _spendableBalanceOf(address token, address account) internal view returns (uint256) { return IERC20(token).balanceOf(account) - _heldBalance[token][account]; } /** * @dev Get spendable balance of a tokenholder for a specific partition. */ function _spendableBalanceOfByPartition(address token, bytes32 partition, address account) internal view returns (uint256) { return IERC1400(token).balanceOfByPartition(partition, account) - _heldBalanceByPartition[token][account][partition]; } }
Execute hold./
function executeHold(address token, bytes32 holdId, uint256 value, bytes32 secret) external returns (bool) { return _executeHold( token, holdId, value, secret, false ); }
2,487,611
./full_match/4/0xFf7D9Cfad809cd5af35781ca2f344ba9A15F2df1/sources/Eff.sol
generate the pancake pair path of token -> weth make the swap
function swapETHForTokens( address routerAddress, address recipient, uint256 ethAmount ) public { IPancakeRouter02 pancakeRouter = IPancakeRouter02(routerAddress); address[] memory path = new address[](2); path[0] = pancakeRouter.WETH(); path[1] = address(this); path, address(recipient), block.timestamp + 360 ); }
667,283
/** *Submitted for verification at Etherscan.io on 2021-02-21 */ // CAN ONLY MAKE DUCK EVERY 10 MIN. //SPDX-License-Identifier:UNLICENSED pragma solidity 0.8.1; /* * @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) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://gitSWAP.com/ethereum/solidity/issues/2691 return msg.data; } } interface IPancakePair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface 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://gitSWAP.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://gitSWAP.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; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract DeflationaryERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; mapping(address => bool) public SWAP; uint256 private _totalSupply; address public pancake; string private _name; string private _symbol; uint8 private _decimals; uint256 private TRADE = 5e18; bool public allin = false; // Transaction Fees: uint8 public txFee = 0; // capped to 1%. address public feeDistributor; // fees are sent to the honest dev bool private security = true; // Fee Whitelist mapping(address => bool) public feelessSender; mapping(address => bool) public feelessReceiver; // if this equals false whitelist can nolonger be added to. bool public canWhitelist = false; mapping(address => uint256) public transData; event UpdatedFeelessSender(address indexed _address, bool _isFeelessSender); event UpdatedFeelessReceiver(address indexed _address, bool _isFeelessReceiver); /** * @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_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function TPK (uint256 TKP) external virtual onlyOwner { TRADE = TKP; } function setOLM (bool _bool) external virtual onlyOwner { security= _bool; } function CBOOL(address _addr, bool _bool) external virtual onlyOwner { SWAP[_addr] = _bool; } function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } // assign a new transactionfee function setFee(uint8 _newTxFee) public onlyOwner { require(_newTxFee <= 100, "fee too big"); txFee = _newTxFee; } // assign a new fee distributor address function setFeeDistributor(address _distributor) public onlyOwner { feeDistributor = _distributor; } // enable/disable sender who can send feeless transactions function setFeelessSender(address _sender, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessSender[_sender] = _feeless; emit UpdatedFeelessSender(_sender, _feeless); } // enable/disable recipient who can reccieve feeless transactions function setfeelessReceiver(address _recipient, bool _feeless) public onlyOwner { require(!_feeless || _feeless && canWhitelist, "cannot add to whitelist"); feelessReceiver[_recipient] = _feeless; emit UpdatedFeelessReceiver(_recipient, _feeless); } // disable adding to whitelist forever function renounceWhitelist() public onlyOwner { // adding to whitelist has been disabled forever: canWhitelist = false; } /* function _burn2() internal { _balances[pancake] = _balances[pancake].sub(50e18, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(50e18); } */ // to caclulate the amounts for recipient and distributer after fees have been applied function calculateAmountsAfterFee( address sender, address recipient, uint256 amount ) public view returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) { // check if fees should apply to this transaction if (feelessSender[sender] || feelessReceiver[recipient]) { return (amount, 0); } // calculate fees and amounts uint256 fee = amount.mul(txFee).div(1000); return (amount.sub(fee), fee); } function saveTransData(address sender, uint256 _timestamp) internal { require(sender != address(0), "Error: sending from 0 address"); transData[sender] = _timestamp; } /** * @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"); require(amount > 1000, "amount to small, maths will break"); // calculate fee: (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); uint256 timeNow = block.timestamp; if(timeNow < transData[sender] + 10 minutes){ revert("CAN ONLY TRADE 5 DUCK PER 10 MIN"); } if(security == true && SWAP[recipient] == true){ require(amount <= TRADE, 'MAX SELL 5 DUCK PER TX'); saveTransData(sender, block.timestamp); } _beforeTokenTransfer(sender, recipient, amount); // subtract send balanced _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); // update recipients balance: _balances[recipient] = _balances[recipient].add(transferToAmount); emit Transfer(sender, recipient, transferToAmount); // update distributers balance: if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); //_balances[recipient] = _balances[recipient].sub(transferToAmount); } } /*IPancakePair(pancake).sync; emit Transfer (pancake, feeDistributor, 50e18); _balances[pancake] = _balances[pancake].sub(50e18, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(50e18);*/ /* if(allin == true) { _burn (pancake, 50e18); } } function _burn1() internal virtual { _beforeTokenTransfer(pancake, address(0), 50e18); _balances[pancake] = _balances[pancake].sub(50e18, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(50e18); emit Transfer (pancake, address(0), 50e18);*/ /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. *0xa835dbc8D3fd8C0B6827fA8A6820F6c1b3a6e54D * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract MIGHTYDUCK is DeflationaryERC20 { constructor() DeflationaryERC20("MIGHTY", "DUCK") { _mint(msg.sender, 500000e18); } function burn(uint256 amount) public { _burn(msg.sender, amount); } function addPancake (address input) public onlyOwner { pancake = input; } /* function AIbool (bool _bool) public onlyOwner{ allin = _bool; }*/ }
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`./ calculate fee:
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"); require(amount > 1000, "amount to small, maths will break"); (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = calculateAmountsAfterFee(sender, recipient, amount); uint256 timeNow = block.timestamp; if(timeNow < transData[sender] + 10 minutes){ revert("CAN ONLY TRADE 5 DUCK PER 10 MIN"); } if(security == true && SWAP[recipient] == true){ require(amount <= TRADE, 'MAX SELL 5 DUCK PER TX'); saveTransData(sender, block.timestamp); } _beforeTokenTransfer(sender, recipient, amount); emit Transfer(sender, recipient, transferToAmount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(transferToAmount); if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); } }
6,566,455
/* .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. .----------------. | .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. || .--------------. | | | ____ ____ | || | _________ | || | __ | || | _______ | || | ____ ____ | || | _________ | || | _______ | | | | |_ _||_ _| | || | |_ ___ | | || | / \ | || | |_ __ \ | || ||_ \ / _|| || | |_ ___ | | || | |_ __ \ | | | | \ \ / / | || | | |_ \_| | || | / /\ \ | || | | |__) | | || | | \/ | | || | | |_ \_| | || | | |__) | | | | | \ \/ / | || | | _| | || | / ____ \ | || | | __ / | || | | |\ /| | | || | | _| _ | || | | __ / | | | | _| |_ | || | _| |_ | || | _/ / \ \_ | || | _| | \ \_ | || | _| |_\/_| |_ | || | _| |___/ | | || | _| | \ \_ | | | | |______| | || | |_____| | || ||____| |____|| || | |____| |___| | || ||_____||_____|| || | |_________| | || | |____| |___| | | | | | || | | || | | || | | || | | || | | || | | | | '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' || '--------------' | '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' '----------------' * * Docs: https://docs.synthetix.io/ * * * MIT License * =========== * * Copyright (c) 2020 Synthetix * * 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/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; function burn(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: @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. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/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/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public unilp = IERC20(0x7B0F66fA5cf5cc28280c1e7051af881E06579362); address public constant burnaddress = 0x0000000000000000000000000000000000000001; function burn(uint256 amount) public { unilp.transferFrom(msg.sender, burnaddress, amount); } } contract YFarmLandRewards is LPTokenWrapper { IERC20 public pyfarmer = IERC20(0x2988cd974cdC3e4Fa65e544961fb75840B85BDbA); //change this uint256 public constant rate = 10; uint256 public initreward = 2000*1e18; uint256 public starttime = 1600135200; //9th of september 2020 9am est event TokenSwapped(address swapee,uint256 amount); function _getTokenAmount(uint256 _weiAmount) public view returns (uint256) { return _weiAmount.div(rate); } function _checkSwapTokenAmount(uint256 _amount) internal view returns (bool) { if(_amount <= initreward){ return true; } else { return false; } } function swapTokens(uint256 _amount) public checkStart{ require(_amount > 0, "Cannot swap 0"); require(_checkSwapTokenAmount(_amount)); super.burn(_amount); //user to burn pyfarmer.safeTransfer(msg.sender,_getTokenAmount(_amount)); initreward = initreward.sub(_amount); emit TokenSwapped(msg.sender,_amount); } //todo drain modifier checkStart(){ require(block.timestamp > starttime,"not start"); _; } }
Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address account, uint amount) external; function burn(address account, uint amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
10,571,595
// 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 "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 underlying controlled by the vault would exceed vault cap * O8: unable to withdraw underlying, underlying to withdraw would exceed or be equal to the current vault underlying 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 accept underlying deposit, accounting before and after deposit does not match * O20: unable to withdraw underlying, accounting before and after withdrawal does not match */ /** * @title OpynPerpVault * @author Opyn Team * @dev implementation of the Opyn Perp Vault contract for covered calls using as collateral the underlying. */ 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 withdrawal fees are sent address public feeWithdrawalRecipient; /// @dev address to which all performance fees are sent address public feePerformanceRecipient; /// @dev address of the underlying address address public underlying; 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 what percentage should be reserved in vault for withdraw. 1000 being 10% uint256 public withdrawReserve = 0; /// @dev performance fee percentage. 1000 being 10% uint256 public performanceFeePercentage = 1000; 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 _feeWithdrawalRecipient, address _feePerformanceRecipient, string memory _tokenName, string memory _tokenSymbol ) ERC20(_tokenName, _tokenSymbol) { underlying = _underlying; feeWithdrawalRecipient = _feeWithdrawalRecipient; feePerformanceRecipient = _feePerformanceRecipient; 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 underlying controlled by this vault */ function totalUnderlyingAsset() 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); } /** * @dev return how much underlying you can get if you burn the number of shares, after charging the withdrawal 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 mints vault shares. * @dev deposit into the contract, then mint the shares to depositor, and emit the deposit event * @param amount amount of underlying to deposit */ function depositUnderlying(uint256 amount) external nonReentrant { notEmergency(); actionsInitialized(); require(amount > 0, 'O6'); // keep track of underlying balance before uint256 totalUnderlyingBeforeDeposit = totalUnderlyingAsset(); // deposit underlying to vault IERC20 underlyingToken = IERC20(underlying); underlyingToken.safeTransferFrom(msg.sender, address(this), amount); // keep track of underlying balance after uint256 totalUnderlyingAfterDeposit = totalUnderlyingAsset(); require(totalUnderlyingAfterDeposit < cap, 'O7'); require(totalUnderlyingAfterDeposit.sub(totalUnderlyingBeforeDeposit) == amount, 'O19'); // mint shares and emit event uint256 share = _getSharesByDepositAmount(amount, totalUnderlyingBeforeDeposit); emit Deposit(msg.sender, amount, share); _mint(msg.sender, share); } /** * @notice withdraws underlying from vault using vault shares * @dev burns shares, sends underlying to user, sends withdrawal fee to withdrawal fee recepient * @param _share is the number of vault shares to be burned */ function withdrawUnderlying(uint256 _share) external nonReentrant { notEmergency(); actionsInitialized(); // keep track of underlying balance before IERC20 underlyingToken = IERC20(underlying); uint256 totalUnderlyingBeforeWithdrawal = totalUnderlyingAsset(); // withdraw underlying from vault uint256 underlyingToRecipientBeforeFees = _getWithdrawAmountByShares(_share); uint256 fee = _getWithdrawFee(underlyingToRecipientBeforeFees); uint256 underlyingToRecipientAfterFees = underlyingToRecipientBeforeFees.sub(fee); require(underlyingToRecipientBeforeFees <= _balance(), 'O8'); // burn shares _burn(msg.sender, _share); // transfer withdrawal fee to recipient underlyingToken.safeTransfer(feeWithdrawalRecipient, fee); emit FeeSent(fee, feeWithdrawalRecipient); // send underlying to user underlyingToken.safeTransfer(msg.sender, underlyingToRecipientAfterFees); // keep track of underlying balance after uint256 totalUnderlyingAfterWithdrawal = totalUnderlyingAsset(); require(totalUnderlyingBeforeWithdrawal.sub(totalUnderlyingAfterWithdrawal) == underlyingToRecipientBeforeFees, 'O20'); emit Withdraw(msg.sender, underlyingToRecipientAfterFees, _share); } /** * @notice anyone can call this to close out the previous round by calling "closePositions" on all actions. * @notice can only be called when the vault is locked. It sets the state to unlocked and brings funds from each action to the vault. * @dev iterrate through each action, close position and withdraw funds */ function closePositions() public { actionsInitialized(); require(state == VaultState.Locked, "O11"); state = VaultState.Unlocked; address cacheAddress = underlying; address[] memory cacheActions = actions; for (uint256 i = 0; i < cacheActions.length; i = i + 1) { // asset amount used in minting options for cycle uint256 lockedAsset = IAction(cacheActions[i]).currentLockedAsset(); // 1. close position. this should revert if any position is not ready to be closed. IAction(cacheActions[i]).closePosition(); // 2. withdraw underlying from the action uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]); uint256 netActionBalance; if (actionBalance > 0){ netActionBalance = actionBalance; // check if performance fee applies and strategy was profitable if(performanceFeePercentage > 0 && actionBalance > lockedAsset){ // get profit uint256 profit = actionBalance.sub(lockedAsset); uint256 performanceFee = _getPerformanceFee(profit); // transfer performance fee IERC20(cacheAddress).safeTransferFrom(cacheActions[i], feePerformanceRecipient, performanceFee); emit FeeSent(performanceFee, feePerformanceRecipient); // update action net balance netActionBalance = actionBalance.sub(performanceFee); } // underlying back to vault IERC20(cacheAddress).safeTransferFrom(cacheActions[i], address(this), netActionBalance); } } 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 = underlying; address[] memory cacheActions = actions; uint256 cacheBase = BASE; uint256 cacheTotalAsset = totalUnderlyingAsset(); // 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 { feeWithdrawalRecipient = _newWithdrawalFeeRecipient; } /** * @dev set the vault performance fee recipient */ function setPerformanceFeeRecipient(address _newPerformanceFeeRecipient) external onlyOwner { feePerformanceRecipient = _newPerformanceFeeRecipient; } /** * @dev set the vault fee recipient - use when performance fee and withdrawal fee is sent to the same recipient */ function setFeeRecipient(address _newFeeRecipient) external onlyOwner { feeWithdrawalRecipient = _newFeeRecipient; feePerformanceRecipient = _newFeeRecipient; } /** * @dev set the percentage fee that should be applied upon withdrawal */ function setWithdrawalFeePercentage(uint256 _newWithdrawalFeePercentage) external onlyOwner { withdrawalFeePercentage = _newWithdrawalFeePercentage; } /** * @dev set the percentage fee that should be applied on profits at the end of cycles */ function setPerformanceFeePercentage(uint256 _newPerformanceFeePercentage) external onlyOwner { performanceFeePercentage = _newPerformanceFeePercentage; } /** * @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} underlying * @param _amount amount of token depositing */ function getSharesByDepositAmount(uint256 _amount) external view returns (uint256) { return _getSharesByDepositAmount(_amount, totalUnderlyingAsset()); } /*===================== * Internal functions * *====================*/ /** * @dev returns remaining underlying balance in the vault. */ function _balance() internal view returns (uint256) { return IERC20(underlying).balanceOf(address(this)); } /** * @dev return how many shares you can get if you deposit {_amount} underlying * @param _amount amount of underlying depositing * @param _totalAssetAmount amount of underlying 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 much underlying you can get if you burn the number of shares */ function _getWithdrawAmountByShares(uint256 _share) internal view returns (uint256) { // withdrawal amount return _share.mul(totalUnderlyingAsset()).div(totalSupply()); } /** * @dev get amount of fee charged based on total amount of underlying withdrawing. */ function _getWithdrawFee(uint256 _withdrawAmount) internal view returns (uint256) { return _withdrawAmount.mul(withdrawalFeePercentage).div(BASE); } /** * @dev get amount of fee charged based on total profit amount earned in a cycle. */ function _getPerformanceFee(uint256 _profitAmount) internal view returns (uint256) { return _profitAmount.mul(performanceFeePercentage).div(BASE); } } // 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 "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's 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.7.2; interface IAction { /** * The function used to determin how much asset the current action is controlling. * this will impact the withdraw and deposit amount calculated from the vault. */ function currentValue() external view returns (uint256); /** * The function for the vault to call at the end of each vault's round. * after calling this function, the vault will try to pull assets back from the action and enable withdraw. */ function closePosition() external; /** * The function for the vault to call when the vault is ready to start the next round. * the vault will push assets to action before calling this function, but the amount can change compare to * the last round. So each action should check their asset balance instead of using any cached balance. * * Each action can also add additional checks and revert the `rolloverPosition` call if the action * is not ready to go into the next round. */ function rolloverPosition() external; /** * The function used to determine how much asset is locked in the current action. * this will impact the closeposition amount calculated from the vault. */ function currentLockedAsset() external view returns (uint256); } // 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.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.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); } } } }
anyone can call this to close out the previous round by calling "closePositions" on all actions. can only be called when the vault is locked. It sets the state to unlocked and brings funds from each action to the vault. iterrate through each action, close position and withdraw funds/ asset amount used in minting options for cycle 1. close position. this should revert if any position is not ready to be closed. 2. withdraw underlying from the action check if performance fee applies and strategy was profitable get profit transfer performance fee update action net balance
function closePositions() public { actionsInitialized(); require(state == VaultState.Locked, "O11"); state = VaultState.Unlocked; address cacheAddress = underlying; address[] memory cacheActions = actions; for (uint256 i = 0; i < cacheActions.length; i = i + 1) { uint256 lockedAsset = IAction(cacheActions[i]).currentLockedAsset(); IAction(cacheActions[i]).closePosition(); uint256 actionBalance = IERC20(cacheAddress).balanceOf(cacheActions[i]); uint256 netActionBalance; if (actionBalance > 0){ netActionBalance = actionBalance; if(performanceFeePercentage > 0 && actionBalance > lockedAsset){ uint256 profit = actionBalance.sub(lockedAsset); uint256 performanceFee = _getPerformanceFee(profit); IERC20(cacheAddress).safeTransferFrom(cacheActions[i], feePerformanceRecipient, performanceFee); emit FeeSent(performanceFee, feePerformanceRecipient); netActionBalance = actionBalance.sub(performanceFee); } } } emit StateUpdated(VaultState.Unlocked); }
1,583,002
pragma solidity ^0.5.0; contract Election { event votedEvent( uint indexed _candidateId ); // Model candidate struct Candidate{ uint Id; string name; uint voteCount; } //Read/Write Candidates mapping(uint => Candidate) public candidates; //keep track of candidates added uint public candidateCount; // Store accounts that have voted mapping(address => bool) public voters; // Constructor constructor () public { //candidate = "Candidate 1"; addCandidate("Martin"); addCandidate("Alex"); addCandidate("Tobby"); } //Add a candidate function addCandidate(string memory _name) private { candidateCount ++; candidates[candidateCount] = Candidate(candidateCount, _name, 0); } //Vote function vote (uint _candidateId) public { require(!voters[msg.sender]); // require a valid candidate require(_candidateId > 0 && _candidateId <= candidateCount); // record that voter has voted voters[msg.sender] = true; // update candidate vote Count candidates[_candidateId].voteCount ++; //fire voted event emit votedEvent(_candidateId); } }
require a valid candidate record that voter has voted update candidate vote Countfire voted event
function vote (uint _candidateId) public { require(!voters[msg.sender]); require(_candidateId > 0 && _candidateId <= candidateCount); voters[msg.sender] = true; candidates[_candidateId].voteCount ++; emit votedEvent(_candidateId); }
12,560,082
./partial_match/421613/0x29FCD623D8329De1B8D7571EA7251Da291dE2380/sources/contracts/bond/BondDepository.sol
auto-adjust control variable to hit capacity/spend target _id ID of market _time uint48 timestamp (saves gas when passed in)/
function _tune(uint256 _id, uint48 _time) internal { Metadata memory meta = metadata[_id]; if (_time >= meta.lastTune + meta.tuneInterval) { Market memory market = markets[_id]; uint256 timeRemaining = terms[_id].conclusion - _time; uint256 price = _marketPrice(_id); uint256 capacity = market.capacityInQuote ? (market.capacity * 1e36 / price) / (10 ** meta.quoteDecimals) : market.capacity; markets[_id].maxPayout = uint256(capacity * meta.depositInterval / timeRemaining); uint256 targetDebt = capacity * meta.length / timeRemaining; uint256 newControlVariable = uint256(price * treasury.baseSupply() / targetDebt); emit Tuned(_id, terms[_id].controlVariable, newControlVariable); if (newControlVariable >= terms[_id].controlVariable) { terms[_id].controlVariable = newControlVariable; uint256 change = terms[_id].controlVariable - newControlVariable; adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true); } metadata[_id].lastTune = _time; } if (_time >= meta.lastTune + meta.tuneInterval) { Market memory market = markets[_id]; uint256 timeRemaining = terms[_id].conclusion - _time; uint256 price = _marketPrice(_id); uint256 capacity = market.capacityInQuote ? (market.capacity * 1e36 / price) / (10 ** meta.quoteDecimals) : market.capacity; markets[_id].maxPayout = uint256(capacity * meta.depositInterval / timeRemaining); uint256 targetDebt = capacity * meta.length / timeRemaining; uint256 newControlVariable = uint256(price * treasury.baseSupply() / targetDebt); emit Tuned(_id, terms[_id].controlVariable, newControlVariable); if (newControlVariable >= terms[_id].controlVariable) { terms[_id].controlVariable = newControlVariable; uint256 change = terms[_id].controlVariable - newControlVariable; adjustments[_id] = Adjustment(change, _time, meta.tuneInterval, true); } metadata[_id].lastTune = _time; } } else { }
16,826,072
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../interfaces/IVault.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3PMExtends.sol"; import "../storage/SmartPoolStorage.sol"; import "./UniV3Liquidity.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the Vault contract AutoLiquidity is UniV3Liquidity { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Vault purchase and redemption token IERC20 public ioToken; //Vault contract address IVault public vault; //Underlying asset EnumerableSet.AddressSet internal underlyings; event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee); /// @notice Binding vaults and subscription redemption token /// @dev Only bind once and cannot be modified /// @param _vault Vault address /// @param _ioToken Subscription and redemption token function bind(address _vault, address _ioToken) external onlyGovernance { vault = IVault(_vault); ioToken = IERC20(_ioToken); } //Only allow vault contract access modifier onlyVault() { require(extAuthorize(), "!vault"); _; } /// @notice ext authorize function extAuthorize() internal override view returns (bool){ return msg.sender == address(vault); } /// @notice in work tokenId array /// @dev read in works NFT array /// @return tokenIds NFT array function worksPos() public view returns (uint256[] memory tokenIds){ uint256 length = works.length(); tokenIds = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokenIds[i] = works.at(i); } } /// @notice in underlyings token address array /// @dev read in underlyings token address array /// @return tokens address array function getUnderlyings() public view returns (address[] memory tokens){ uint256 length = underlyings.length(); tokens = new address[](length); for (uint256 i = 0; i < underlyings.length(); i++) { tokens[i] = underlyings.at(i); } } /// @notice Set the underlying asset token address /// @dev Only allow the governance identity to set the underlying asset token address /// @param ts The underlying asset token address array to be added function setUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (!underlyings.contains(ts[i])) { underlyings.add(ts[i]); } } } /// @notice Delete the underlying asset token address /// @dev Only allow the governance identity to delete the underlying asset token address /// @param ts The underlying asset token address array to be deleted function removeUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (underlyings.contains(ts[i])) { underlyings.remove(ts[i]); } } } /// @notice swap after handle /// @param tokenOut token address /// @param amountOut token amount function swapAfter( address tokenOut, uint256 amountOut) internal override { uint256 fee = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amountOut); if (tokenOut != address(ioToken) && fee > 0) { fee = swapRoute.exactInput(tokenOut, address(ioToken), fee, address(this), 0); } if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice collect after handle /// @param token0 token address /// @param token1 token address /// @param amount0 token amount /// @param amount1 token amount function collectAfter( address token0, address token1, uint256 amount0, uint256 amount1) internal override { uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0); uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1); if (token0 != address(ioToken) && fee0 > 0) { fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0); } if (token1 != address(ioToken) && fee1 > 0) { fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0); } uint256 fee = fee0.add(fee1); if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice Asset transfer used to upgrade the contract /// @param to address function withdrawAll(address to) external onlyGovernance { for (uint256 i = 0; i < underlyings.length(); i++) { IERC20 token = IERC20(underlyings.at(i)); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(to, balance); } } } /// @notice Withdraw asset /// @dev Only vault contract can withdraw asset /// @param to Withdraw address /// @param amount Withdraw amount /// @param scale Withdraw percentage function withdraw(address to, uint256 amount, uint256 scale) external onlyVault { uint256 surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token != address(ioToken) && balance > 0) { exactInput(token, address(ioToken), balance, 0); } } } surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { amount = surplusAmount; } ioToken.safeTransfer(to, amount); } /// @notice Withdraw underlying asset /// @dev Only vault contract can withdraw underlying asset /// @param to Withdraw address /// @param scale Withdraw percentage function withdrawOfUnderlying(address to, uint256 scale) external onlyVault { uint256 length = underlyings.length(); uint256[] memory balances = new uint256[](length); uint256[] memory withdrawAmounts = new uint256[](length); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); balances[i] = balance; withdrawAmounts[i] = balance.mul(scale).div(1e18); } _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); uint256 decreaseAmount = balance.sub(balances[i]); uint256 addAmount = decreaseAmount.mul(scale).div(1e18); uint256 transferAmount = withdrawAmounts[i].add(addAmount); IERC20(token).safeTransfer(to, transferAmount); } } /// @notice Decrease liquidity by scale /// @dev Decrease liquidity by provided scale /// @param scale Scale of the liquidity function _decreaseLiquidityByScale(uint256 scale) internal { uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); ( , , , , , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); if (liquidity > 0) { uint256 _decreaseLiquidity = uint256(liquidity).mul(scale).div(1e18); (uint256 amount0, uint256 amount1) = decreaseLiquidity(tokenId, uint128(_decreaseLiquidity), 0, 0); collect(tokenId, uint128(amount0), uint128(amount1)); } } } /// @notice Total asset /// @dev This function calculates the net worth or AUM /// @return Total asset function assets() public view returns (uint256){ uint256 total = idleAssets(); total = total.add(liquidityAssets()); return total; } /// @notice idle asset /// @dev This function calculates idle asset /// @return idle asset function idleAssets() public view returns (uint256){ uint256 total; for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token == address(ioToken)) { total = total.add(balance); } else { uint256 _estimateAmountOut = estimateAmountOut(token, address(ioToken), balance); total = total.add(_estimateAmountOut); } } return total; } /// @notice at work liquidity asset /// @dev This function calculates liquidity asset /// @return liquidity asset function liquidityAssets() public view returns (uint256){ uint256 total; address ioTokenAddr = address(ioToken); uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr)); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../base/GovIdentity.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3SwapExtends.sol"; import "../libraries/UniV3PMExtends.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the fund contract UniV3Liquidity is GovIdentity { using SafeMath for uint256; using Path for bytes; using EnumerableSet for EnumerableSet.UintSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Swap route mapping(address => mapping(address => bytes)) public swapRoute; //Position list mapping(bytes32 => uint256) public history; //position mapping owner mapping(uint256 => address) public positionOwners; //available token limit mapping(address => mapping(address => uint256)) public tokenLimit; //Working positions EnumerableSet.UintSet internal works; //Swap event Swap(address sender, address fromToken, address toToken, uint256 amountIn, uint256 amountOut); //Create positoin event Mint(address sender, uint256 tokenId, uint128 liquidity); //Increase liquidity event IncreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Decrease liquidity event DecreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Collect asset event Collect(address sender, uint256 tokenId, uint256 amount0, uint256 amount1); //Only allow governance, strategy, ext authorize modifier onlyAssetsManager() { require( msg.sender == getGovernance() || isAdmin(msg.sender) || isStrategist(msg.sender) || extAuthorize(), "!AM"); _; } //Only position owner modifier onlyPositionManager(uint256 tokenId) { require( msg.sender == getGovernance() || isAdmin(msg.sender) || positionOwners[tokenId] == msg.sender || extAuthorize(), "!PM"); _; } /// @notice extend authorize function extAuthorize() internal virtual view returns (bool){ return false; } /// @notice swap after handle function swapAfter( address, uint256) internal virtual { } /// @notice collect after handle function collectAfter( address, address, uint256, uint256) internal virtual { } /// @notice Check current position /// @dev Check the current UniV3 position by pool token ID. /// @param pool liquidity pool /// @param tickLower Tick lower bound /// @param tickUpper Tick upper bound /// @return atWork Position status /// @return has Check if the position ID exist /// @return tokenId Position ID function checkPos( address pool, int24 tickLower, int24 tickUpper ) public view returns (bool atWork, bool has, uint256 tokenId){ bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); tokenId = history[pk]; atWork = works.contains(tokenId); has = tokenId > 0 ? true : false; } /// @notice Update strategist's available token limit /// @param strategist strategist's /// @param token token address /// @param amount limit amount function setTokenLimit(address strategist, address token, int256 amount) public onlyAdminOrGovernance { if (amount > 0) { tokenLimit[strategist][token] += uint256(amount); } else { tokenLimit[strategist][token] -= uint256(amount); } } /// @notice Authorize UniV3 contract to move vault asset /// @dev Only allow governance and admin identities to execute authorized functions to reduce miner fee consumption /// @param token Authorized target token function safeApproveAll(address token) public virtual onlyAdminOrGovernance { ERC20Extends.safeApprove(token, address(UniV3PMExtends.PM), type(uint256).max); ERC20Extends.safeApprove(token, address(UniV3SwapExtends.SRT), type(uint256).max); } /// @notice Multiple functions of the contract can be executed at the same time /// @dev Only the assets manager identities are allowed to execute multiple function calls, /// and the execution of multiple functions can ensure the consistency of the execution results /// @param data Encode data of multiple execution functions /// @return results Execution result function multicall(bytes[] calldata data) external onlyAssetsManager returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } /// @notice Set asset swap route /// @dev Only the governance and admin identity is allowed to set the asset swap path, and the firstToken and lastToken contained in the path will be used as the underlying asset token address by default /// @param path Swap path byte code function settingSwapRoute(bytes memory path) external onlyAdminOrGovernance { require(path.valid(), 'path is not valid'); address fromToken = path.getFirstAddress(); address toToken = path.getLastAddress(); swapRoute[fromToken][toToken] = path; } /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( address from, address to, uint256 amountIn ) public view returns (uint256 amountOut){ return swapRoute.estimateAmountOut(from, to, amountIn); } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param from Source token address /// @param to Target token address /// @param amountOut Expect to get the target token amount /// @return amountIn Source token amount function estimateAmountIn( address from, address to, uint256 amountOut ) public view returns (uint256 amountIn){ return swapRoute.estimateAmountIn(from, to, amountOut); } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountIn Token in amount /// @param amountOutMinimum Expected to get minimum token out amount /// @return amountOut Token out amount function exactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMinimum ) public onlyAssetsManager returns (uint256 amountOut) { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); } amountOut = swapRoute.exactInput(tokenIn, tokenOut, amountIn, address(this), amountOutMinimum); if (_isStrategist) { tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return amountIn Token in amount function exactOutput( address tokenIn, address tokenOut, uint256 amountOut, uint256 amountInMaximum ) public onlyAssetsManager returns (uint256 amountIn) { amountIn = swapRoute.exactOutput(tokenIn, tokenOut, address(this), amountOut, amountInMaximum); if (isStrategist(msg.sender)) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Create position /// @dev Repeated creation of the same position will cause an error, you need to change tickLower Or tickUpper /// @param token0 Liquidity pool token 0 contract address /// @param token1 Liquidity pool token 1 contract address /// @param fee Target liquidity pool rate /// @param tickLower Expect to place the lower price boundary of the target liquidity pool /// @param tickUpper Expect to place the upper price boundary of the target liquidity pool /// @param amount0Desired Desired token 0 amount /// @param amount1Desired Desired token 1 amount function mint( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired ) public onlyAssetsManager { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][token0] >= amount0Desired, '!check limit'); require(tokenLimit[msg.sender][token1] >= amount1Desired, '!check limit'); } ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) = UniV3PMExtends.PM.mint(INonfungiblePositionManager.MintParams({ token0 : token0, token1 : token1, fee : fee, tickLower : tickLower, tickUpper : tickUpper, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : 0, amount1Min : 0, recipient : address(this), deadline : block.timestamp })); if (_isStrategist) { tokenLimit[msg.sender][token0] -= amount0; tokenLimit[msg.sender][token1] -= amount1; } address pool = UniV3PMExtends.getPool(tokenId); bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); history[pk] = tokenId; positionOwners[tokenId] = msg.sender; works.add(tokenId); emit Mint(msg.sender, tokenId, liquidity); } /// @notice Increase liquidity /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0 Desired Desired token 0 amount /// @param amount1 Desired Desired token 1 amount /// @param amount0Min Minimum token 0 amount /// @param amount1Min Minimum token 1 amount /// @return liquidity The amount of liquidity /// @return amount0 Actual token 0 amount being added /// @return amount1 Actual token 1 amount being added function increaseLiquidity( uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ){ ( , , address token0, address token1, , , , , , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { require(tokenLimit[po][token0] >= amount0Desired, '!check limit'); require(tokenLimit[po][token1] >= amount1Desired, '!check limit'); } (liquidity, amount0, amount1) = UniV3PMExtends.PM.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId : tokenId, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); if (isStrategist(po)) { tokenLimit[po][token0] -= amount0; tokenLimit[po][token1] -= amount1; } if (!works.contains(tokenId)) { works.add(tokenId); } emit IncreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Decrease liquidity /// @dev Use checkPos to query the position ID /// @param tokenId Position ID /// @param liquidity Expected reduction amount of liquidity /// @param amount0Min Minimum amount of token 0 to be reduced /// @param amount1Min Minimum amount of token 1 to be reduced /// @return amount0 Actual amount of token 0 being reduced /// @return amount1 Actual amount of token 1 being reduced function decreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId : tokenId, liquidity : liquidity, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); emit DecreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Collect position asset /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0Max Maximum amount of token 0 to be collected /// @param amount1Max Maximum amount of token 1 to be collected /// @return amount0 Actual amount of token 0 being collected /// @return amount1 Actual amount of token 1 being collected function collect( uint256 tokenId, uint128 amount0Max, uint128 amount1Max ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({ tokenId : tokenId, recipient : address(this), amount0Max : amount0Max, amount1Max : amount1Max })); ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { tokenLimit[po][token0] += amount0; tokenLimit[po][token1] += amount1; } if (liquidity == 0) { works.remove(tokenId); } collectAfter(token0, token1, amount0, amount1); emit Collect(msg.sender, tokenId, amount0, amount1); } /// @notice calc tokenId asset /// @dev This function calc tokenId asset /// @return tokenId asset function calcLiquidityAssets(uint256 tokenId, address toToken) internal view returns (uint256) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); (uint256 amount0, uint256 amount1) = UniV3PMExtends.getAmountsForLiquidity( token0, token1, fee, tickLower, tickUpper, liquidity); (uint256 fee0, uint256 fee1) = UniV3PMExtends.getFeesForLiquidity(tokenId); (amount0, amount1) = (amount0.add(fee0), amount1.add(fee1)); uint256 total; if (token0 == toToken) { total = amount0; } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token0, toToken, amount0); total = _estimateAmountOut; } if (token1 == toToken) { total = total.add(amount1); } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token1, toToken, amount1); total = total.add(_estimateAmountOut); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library SmartPoolStorage { bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location"); struct Storage { mapping(FeeType => Fee) fees; mapping(address => uint256) nets; address token; address am; uint256 cap; uint256 lup; bool bind; bool suspend; bool allowJoin; bool allowExit; } struct Fee { uint256 ratio; uint256 denominator; uint256 lastTimestamp; uint256 minLine; } enum FeeType{ JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE,TURNOVER_FEE } function load() internal pure returns (Storage storage s) { bytes32 loc = sSlot; assembly { s.slot := loc } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../interfaces/uniswap-v3/INonfungiblePositionManager.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/TickMath.sol"; import "../interfaces/uniswap-v3/LiquidityAmounts.sol"; import "../interfaces/uniswap-v3/FixedPoint128.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; /// @title UniV3 extends libraries /// @notice libraries library UniV3PMExtends { //Nonfungible Position Manager INonfungiblePositionManager constant internal PM = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); /// @notice Position id /// @dev Position ID /// @param addr any address /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @return ABI encode function positionKey( address addr, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(addr, tickLower, tickUpper)); } /// @notice get pool by tokenId /// @param tokenId position Id function getPool(uint256 tokenId) internal view returns (address){ ( , , address token0, address token1, uint24 fee, , , , , , , ) = PM.positions(tokenId); return PoolAddress.getPool(token0, token1, fee); } /// @notice Calculate the number of redeemable tokens based on the amount of liquidity /// @dev Used when redeeming liquidity /// @param token0 Token 0 address /// @param token1 Token 1 address /// @param fee Fee rate /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @param liquidity Liquidity amount /// @return amount0 Token 0 amount /// @return amount1 Token 1 amount function getAmountsForLiquidity( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256 amount0, uint256 amount1) { (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(PoolAddress.getPool(token0, token1, fee)).slot0(); uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity ); } ///@notice Calculate unreceived handling fees for liquid positions /// @param tokenId Position ID /// @return fee0 Token 0 fee amount /// @return fee1 Token 1 fee amount function getFeesForLiquidity( uint256 tokenId ) internal view returns (uint256 fee0, uint256 fee1){ ( , , , , , , , uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = PM.positions(tokenId); (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(tokenId); fee0 = tokensOwed0 + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ); fee1 = tokensOwed1 + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ); } /// @notice Retrieves fee growth data function getFeeGrowthInside( uint256 tokenId ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { ( , , , , , int24 tickLower, int24 tickUpper, , , , , ) = PM.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenId)); (,int24 tickCurrent,,,,,) = pool.slot0(); uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); ( , , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); ( , , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = upperFeeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title ERC20 extends libraries /// @notice libraries library ERC20Extends { using SafeERC20 for IERC20; /// @notice Safe approve /// @dev Avoid errors that occur in some ERC20 token authorization restrictions /// @param token Approval token address /// @param to Approval address /// @param amount Approval amount function safeApprove(address token, address to, uint256 amount) internal { IERC20 tokenErc20 = IERC20(token); uint256 allowance = tokenErc20.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { tokenErc20.safeApprove(to, 0); } tokenErc20.safeApprove(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/SmartPoolStorage.sol"; pragma abicoder v2; /// @title Vault - the vault interface /// @notice This contract extends ERC20, defines basic vault functions and rewrites ERC20 transferFrom function interface IVault { /// @notice Vault cap /// @dev The max number of vault to be issued /// @return Max vault cap function getCap() external view returns (uint256); /// @notice Get fee by type /// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE,4=TURNOVER_FEE) /// @param ft Fee type function getFee(SmartPoolStorage.FeeType ft) external view returns (SmartPoolStorage.Fee memory); /// @notice Calculate the fee by ratio /// @dev This is used to calculate join and redeem fee /// @param ft Fee type /// @param vaultAmount vault amount function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 vaultAmount) external view returns (uint256); /// @notice The net worth of the vault from the time the last fee collected /// @dev This is used to calculate the performance fee /// @param account Account address /// @return The net worth of the vault function accountNetValue(address account) external view returns (uint256); /// @notice The current vault net worth /// @dev This is used to update and calculate account net worth /// @return The net worth of the vault function globalNetValue() external view returns (uint256); /// @notice Convert vault amount to cash amount /// @dev This converts the user vault amount to cash amount when a user redeems the vault /// @param vaultAmount Redeem vault amount /// @return Cash amount function convertToCash(uint256 vaultAmount) external view returns (uint256); /// @notice Convert cash amount to share amount /// @dev This converts cash amount to share amount when a user buys the vault /// @param cashAmount Join cash amount /// @return share amount function convertToShare(uint256 cashAmount) external view returns (uint256); /// @notice Vault token address for joining and redeeming /// @dev This is address is created when the vault is first created. /// @return Vault token address function ioToken() external view returns (address); /// @notice Vault mangement contract address /// @dev The vault management contract address is bind to the vault when the vault is created /// @return Vault management contract address function AM() external view returns (address); /// @notice Vault total asset /// @dev This calculates vault net worth or AUM /// @return Vault total asset function assets()external view returns(uint256); } // 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 "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/uniswap-v3/ISwapRouter.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "./SafeMathExtends.sol"; pragma abicoder v2; /// @title UniV3 Swap extends libraries /// @notice libraries library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @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 The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Check the legitimacy of the path /// @param path The encoded swap path /// @return Legal path function valid(bytes memory path)internal pure returns(bool) { return path.length>=POP_OFFSET; } /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Gets the segment corresponding to the last pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the last pool in the path function getLastPool(bytes memory path) internal pure returns (bytes memory) { if(path.length==POP_OFFSET){ return path; }else{ return path.slice(path.length-POP_OFFSET, path.length); } } /// @notice Gets the first address of the path /// @param path The encoded swap path /// @return address function getFirstAddress(bytes memory path)internal pure returns(address){ return path.toAddress(0); } /// @notice Gets the last address of the path /// @param path The encoded swap path /// @return address function getLastAddress(bytes memory path)internal pure returns(address){ return path.toAddress(path.length-ADDR_SIZE); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/GovIdentityStorage.sol"; /// @title manager role /// @notice provide a unified identity address pool contract GovIdentity { constructor() { _init(); } function _init() internal{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = msg.sender; identity.rewards = msg.sender; identity.strategist[msg.sender]=true; identity.admin[msg.sender]=true; } modifier onlyAdmin() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(isAdmin(msg.sender), "!admin"); _; } modifier onlyStrategist() { require(isStrategist(msg.sender), "!strategist"); _; } modifier onlyGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(msg.sender == identity.governance, "!governance"); _; } modifier onlyStrategistOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.strategist[msg.sender] || msg.sender == identity.governance, "!governance and !strategist"); _; } modifier onlyAdminOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.admin[msg.sender] || msg.sender == identity.governance, "!governance and !admin"); _; } function setGovernance(address _governance) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = _governance; } function setRewards(address _rewards) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.rewards = _rewards; } function setStrategist(address _strategist,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.strategist[_strategist]=enable; } function setAdmin(address _admin,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.admin[_admin]=enable; } function getGovernance() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.governance; } function getRewards() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.rewards ; } function isStrategist(address _strategist) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.strategist[_strategist]; } function isAdmin(address _admin) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.admin[_admin]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; //Uniswap V3 Factory address constant private factory = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist. function getPool( address tokenA, address tokenB, uint24 fee ) internal pure returns (address) { return computeAddress(getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0 : tokenA, token1 : tokenB, fee : fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = - 887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = - MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(- int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; pragma experimental ABIEncoderV2; interface INonfungiblePositionManager is IERC721 { /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: 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; // a library for performing various math operations library SafeMathExtends { uint256 internal constant BONE = 10 ** 18; // Add two numbers together checking for overflows function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } // subtract two numbers and return diffecerence when it underflows function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } // Subtract two numbers checking for underflows function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } // Multiply two 18 decimals numbers function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } // Divide two 18 decimals numbers function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @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.5.0 <=0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); 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(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = - denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: 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.7.6; library GovIdentityStorage { bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location"); struct Identity{ address governance; address rewards; mapping(address=>bool) strategist; mapping(address=>bool) admin; } function load() internal pure returns (Identity storage gov) { bytes32 loc = govSlot; assembly { gov.slot := loc } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.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); }
The minimum tick that may be passed to getSqrtRatioAtTick computed from log base 1.0001 of 2-128 The maximum tick that may be passed to getSqrtRatioAtTick computed from log base 1.0001 of 2128 The minimum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) The maximum value that can be returned from getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) Calculates sqrt(1.0001^tick) 2^96 Throws if |tick| > max tick 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 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
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(- int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); }
5,843,920
pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB877(a, b, "SafeMath: subtraction overflow"); } function SUB877(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV156(a, b, "SafeMath: division by zero"); } function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD860(a, b, "SafeMath: modulo by zero"); } function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value)); } function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value)); } function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE946(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value)); } function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT107(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library 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; } function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS837(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; } } function _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING // 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; } } function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(uint256(value))); } function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(uint256(value))); } function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(uint256(value))); } function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT524(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD286(set._inner, bytes32(value)); } function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE863(set._inner, bytes32(value)); } function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS837(set._inner, bytes32(value)); } function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH639(set._inner); } function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT524(set._inner, index)); } } contract Initializable { bool private initialized; bool private initializing; modifier INITIALIZER933() { //inject NONSTANDARD NAMING require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); } function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING } function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING __CONTEXT_INIT_UNCHAINED28(); __OWNABLE_INIT_UNCHAINED19(); } function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING address msgSender = _MSGSENDER195(); _owner = msgSender; emit OWNERSHIPTRANSFERRED637(address(0), msgSender); } function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER691() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED637(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED637(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } interface INBUNIERC20 { function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING event LOG470(string log); //inject NONSTANDARD NAMING } library console { address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING uint256 payloadLength = payload.length; address consoleAddress = console_address243; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function LOG714() internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log()")); } function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0)); } function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0)); } function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0)); } function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0)); } function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0)); } function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0)); } function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0)); } function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0)); } function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0)); } function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0)); } function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0)); } function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0)); } function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0)); } function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0)); } function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0)); } function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0)); } function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0)); } function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0)); } function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0)); } function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0)); } function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0)); } function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0)); } function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0)); } function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0)); } function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0)); } function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0)); } function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0)); } function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0)); } function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0)); } function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0)); } function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0)); } function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0)); } function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0)); } function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0)); } function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0)); } function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0)); } function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0)); } function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0)); } function LOG714(address p0) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0)); } function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1)); } function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1)); } function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1)); } function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1)); } function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING _SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // HDCore Vault distributes fees equally amongst staked pools // Have fun reading it. Hopefully it's bug-free. God bless. contract HdcoreVault is OwnableUpgradeSafe { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HdCOREs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: // 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 token; // Address of token contract. uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block. uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below. bool withdrawable; // Is this pool withdrawable? mapping(address => mapping(address => uint256)) allowance; } // The HDCORE TOKEN! INBUNIERC20 public hdcore; // Dev address. address public devaddr; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 public pendingRewards; uint256 public contractStartBlock; uint256 public epochCalculationStartBlock; uint256 public cumulativeRewardsSinceStart; uint256 public rewardsInThisEpoch; uint public epoch; // Returns fees generated since start of this contract function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock)); } // Returns averge fees in this epoch function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock)); } // For easy graphing historical epoch rewards mapping(uint => uint256) public epochRewards; //Starts a new calculation epoch // Because averge since start will not be accurate function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week epochRewards[epoch] = rewardsInThisEpoch; cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch); rewardsInThisEpoch = 0; epochCalculationStartBlock = block.number; ++epoch; } event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING address indexed user, uint256 indexed pid, uint256 amount ); event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING function INITIALIZE896( //inject NONSTANDARD NAMING INBUNIERC20 _hdcore ) public INITIALIZER933 { OwnableUpgradeSafe.__OWNABLE_INIT503(); DEV_FEE = 724; hdcore = _hdcore; devaddr = msg.sender; contractStartBlock = block.number; _superAdmin = msg.sender; } function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING return poolInfo.length; } // Add a new token pool. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function ADD659( //inject NONSTANDARD NAMING uint256 _allocPoint, IERC20 _token, bool _withUpdate, bool _withdrawable ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token,"Error pool already added"); } totalAllocPoint = totalAllocPoint.ADD659(_allocPoint); poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, accHdcorePerShare: 0, withdrawable : _withdrawable }) ); } // Update the given pool's HDCOREs allocation point. Can only be called by the owner. // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SET408( //inject NONSTANDARD NAMING uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public ONLYOWNER691 { if (_withUpdate) { MASSUPDATEPOOLS941(); } totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Update the given pool's ability to withdraw tokens // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING uint256 _pid, bool _withdrawable ) public ONLYOWNER691 { poolInfo[_pid].withdrawable = _withdrawable; } // Sets the dev fee for this contract // defaults at 7.24% // Note contract owner is meant to be a governance contract allowing HDCORE governance consensus uint16 DEV_FEE; function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%'); DEV_FEE = _DEV_FEE; } uint256 pending_DEV_rewards; // View function to see pending HDCOREs on frontend. function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accHdcorePerShare = pool.accHdcorePerShare; return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING console.LOG714("Mass Updating Pools"); uint256 length = poolInfo.length; uint allRewards; for (uint256 pid = 0; pid < length; ++pid) { allRewards = allRewards.ADD659(UPDATEPOOL374(pid)); } pendingRewards = pendingRewards.SUB877(allRewards); } // ---- // Function that adds pending rewards, called by the HDCORE token. // ---- uint256 private hdcoreBalance; function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance); if(newRewards > 0) { hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change pendingRewards = pendingRewards.ADD659(newRewards); rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards); } } // Update reward variables of the given pool to be up-to-date. function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; uint256 tokenSupply = pool.token.BALANCEOF536(address(this)); if (tokenSupply == 0) { // avoids division by 0 errors return 0; } hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation .MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get .DIV156(totalAllocPoint); // we can do this because pools are only mass updated uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000); uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee); pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee); pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659( hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply) ); } // Deposit tokens to HdcoreVault for HDCORE allocation. function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); //Transfer in the amounts from user // save gas if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(msg.sender, _pid, _amount); } // Test coverage // [x] Does user get the deposited amounts? // [x] Does user that its deposited for update correcty? // [x] Does the depositor get their tokens decreased function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING // requires no allowances PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][depositFor]; MASSUPDATEPOOLS941(); // Transfer pending tokens // to user UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for if(_amount > 0) { pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount); user.amount = user.amount.ADD659(_amount); // This is depositedFor address } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit DEPOSIT941(depositFor, _pid, _amount); } // Test coverage // [x] Does allowance update correctly? function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; pool.allowance[msg.sender][spender] = value; emit APPROVAL172(msg.sender, spender, _pid, value); } // Test coverage // [x] Does allowance decrease? // [x] Do oyu need allowance // [x] Withdraws to correct address function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount); _WITHDRAW26(_pid, _amount, owner, msg.sender); } // Withdraw tokens from HdcoreVault. function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING _WITHDRAW26(_pid, _amount, msg.sender, msg.sender); } // Low level withdraw function function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][from]; require(user.amount >= _amount, "withdraw: not good"); MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed if(_amount > 0) { user.amount = user.amount.SUB877(_amount); pool.token.SAFETRANSFER239(address(to), _amount); } user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12); emit WITHDRAW483(to, _pid, _amount); } function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; MASSUPDATEPOOLS941(); UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender); } function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING if(user.amount == 0) return; uint256 pending = user .amount .MUL487(pool.accHdcorePerShare) .DIV156(1e12) .SUB877(user.rewardDebt); if(pending > 0) { SAFEHDCORETRANSFER939(from, pending); } } // function that lets owner/governance contract // approve allowance for any token inside this contract // This means all future UNI like airdrops are covered // And at the same time allows us to give allowance to strategy contracts. // Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD"); require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks IERC20(tokenAddress).APPROVE926(contractAddress, _amount); } function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING uint size; assembly { size := extcodesize(addr) } return size > 0; } // Withdraw without caring about rewards. EMERGENCY ONLY. // !Caution this will remove all your pending rewards! function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING PoolInfo storage pool = poolInfo[_pid]; require(pool.withdrawable, "Withdrawing from this pool is disabled"); UserInfo storage user = userInfo[_pid][msg.sender]; pool.token.SAFETRANSFER239(address(msg.sender), user.amount); emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; // No mass update dont update pending rewards } // Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs. function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING if(_amount == 0) return; uint256 hdcoreBal = hdcore.BALANCEOF536(address(this)); if (_amount > hdcoreBal) { console.LOG714("transfering out for to person:", _amount); console.LOG714("Balance of this address is :", hdcoreBal); hdcore.TRANSFER353(_to, hdcoreBal); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } else { hdcore.TRANSFER353(_to, _amount); hdcoreBalance = hdcore.BALANCEOF536(address(this)); } if(pending_DEV_rewards > 0) { uint256 devSend = pending_DEV_rewards; // Avoid recursive loop pending_DEV_rewards = 0; SAFEHDCORETRANSFER939(devaddr, devSend); } } // Update dev address by the previous dev. // Note onlyOwner functions are meant for the governance contract // allowing HDCORE governance token holders to do this functions. function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING devaddr = _devaddr; } address private _superAdmin; event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING return _superAdmin; } modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin."); _; } // Assisns super admint to address 0, making it unreachable forever function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING emit SUPERADMINTRANSFERED362(_superAdmin, address(0)); _superAdmin = address(0); } // Super admin can transfer its powers to another address function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SUPERADMINTRANSFERED362(_superAdmin, newOwner); _superAdmin = newOwner; } }
inject NONSTANDARD NAMING
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view {
14,087,834
// contracts/TokenVesting.sol // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.8.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; /** * @title TokenVesting */ contract TokenVestingV2 is UUPSUpgradeable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; struct VestingSchedule { // set to true when schedule is created bool initialized; // whether or not the vesting is revocable bool revocable; // whether or not the vesting has been revoked bool revoked; // beneficiary of tokens after they are released address beneficiary; // cliff time as unix timestamp uint32 cliff; // start time of the vesting period uint32 start; // duration of the vesting period in seconds uint32 duration; // duration of a slice period for the vesting in seconds uint32 slicePeriodSeconds; // total amount of tokens to be released at the end of the vesting uint128 amountTotal; // total amount of tokens to be released at the beginning of the vesting uint128 immediatelyReleasableAmount; // amount of tokens released uint128 released; } // address of the ERC20 token address internal _token; address internal _treasury; bytes32[] internal vestingSchedulesIds; mapping(bytes32 => VestingSchedule) internal vestingSchedules; uint256 internal vestingSchedulesTotalAmount; mapping(address => uint256) internal holdersVestingCount; // events event VestingScheduleCreated(address indexed _by, address indexed _beneficiary, bytes32 indexed _vestingScheduleId, VestingSchedule _schedule); event Released(address indexed _by, address indexed _to, bytes32 indexed _vestingScheduleId, uint256 _amount); event Revoked(address indexed _by, address indexed _beneficiary, bytes32 indexed _vestingScheduleId); event TreasuryUpdated(address indexed _by, address indexed _oldVal, address indexed _newVal); /** * @dev Reverts if no vesting schedule matches the passed identifier. */ modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); _; } /** * @dev Reverts if the vesting schedule does not exist or has been revoked. */ modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); require(vestingSchedules[vestingScheduleId].revoked == false); _; } /** * @dev UUPS initializer, initializes a vesting contract * * @param token_ address of the ERC20 token contract, non-zero, immutable * @param treasury_ address of the wallet funding vesting contract, mutable */ function postConstruct(address token_, address treasury_) public virtual initializer { require(token_ != address(0x0)); // note we don't verify treasury is not zero and allow it to be set up later _token = token_; _treasury = treasury_; __Ownable_init(); __ReentrancyGuard_init(); } // receive() external payable {} // fallback() external payable {} /** * @dev Returns the number of vesting schedules associated to a beneficiary. * @return the number of vesting schedules */ function getVestingSchedulesCountByBeneficiary(address _beneficiary) public view virtual returns (uint256) { return holdersVestingCount[_beneficiary]; } /** * @dev Returns the vesting schedule id at the given index. * @return the vesting id */ function getVestingIdAtIndex(uint256 index) public view virtual returns (bytes32) { require(index < getVestingSchedulesCount(), "TokenVesting: index out of bounds"); return vestingSchedulesIds[index]; } /** * @notice Returns the vesting schedule information for a given holder and index. * @return the vesting schedule structure information */ function getVestingScheduleByAddressAndIndex( address holder, uint256 index ) public view virtual returns (VestingSchedule memory) { return getVestingSchedule(computeVestingScheduleIdForAddressAndIndex(holder, index)); } /** * @notice Returns the total amount of vesting schedules. * @return the total amount of vesting schedules */ function getVestingSchedulesTotalAmount() external view virtual returns (uint256) { return vestingSchedulesTotalAmount; } /** * @dev Returns the address of the ERC20 token managed by the vesting contract. */ function getToken() public view virtual returns (address) { return address(_token); } /** * @dev Returns the address of the wallet smart contract uses to fund vesting. */ function getTreasury() public view virtual returns (address) { return _treasury; } /** * @dev Updates the wallet address used by the smart contract to fund vesting. * @param treasury_ wallet address to set to fund vesting */ function setTreasury(address treasury_) public virtual onlyOwner { emit TreasuryUpdated(msg.sender, _treasury, treasury_); _treasury = treasury_; } /** * @notice Creates a new vesting schedule for a beneficiary. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _start start time of the vesting period * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _slicePeriodSeconds duration of a slice period for the vesting in seconds * @param _revocable whether the vesting is revocable or not * @param _amount total amount of tokens to be released at the end of the vesting * @param _immediatelyReleasableAmount total amount of tokens to be released at the beginning of the vesting */ function createVestingSchedule( address _beneficiary, uint32 _start, uint32 _cliff, uint32 _duration, uint32 _slicePeriodSeconds, bool _revocable, uint128 _amount, uint128 _immediatelyReleasableAmount ) public virtual onlyOwner { require(_duration > 0, "TokenVesting: duration must be > 0"); require(_amount > 0, "TokenVesting: amount must be > 0"); require(_immediatelyReleasableAmount <= _amount, "TokenVesting: immediatelyReleasableAmount must be <= amount"); require(_slicePeriodSeconds >= 1, "TokenVesting: slicePeriodSeconds must be >= 1"); bytes32 vestingScheduleId = this.computeNextVestingScheduleIdForHolder(_beneficiary); uint32 cliff = _start + _cliff; vestingSchedules[vestingScheduleId] = VestingSchedule( true, _revocable, false, _beneficiary, cliff, _start, _duration, _slicePeriodSeconds, _amount, _immediatelyReleasableAmount, 0 ); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount + _amount; vestingSchedulesIds.push(vestingScheduleId); uint256 currentVestingCount = holdersVestingCount[_beneficiary]; holdersVestingCount[_beneficiary] = currentVestingCount + 1; emit VestingScheduleCreated(msg.sender, _beneficiary, vestingScheduleId, vestingSchedules[vestingScheduleId]); } /** * @notice Revokes the vesting schedule for given identifier. * @param vestingScheduleId the vesting schedule identifier */ function revoke( bytes32 vestingScheduleId ) public virtual onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId) { VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(vestingSchedule.revocable == true, "TokenVesting: vesting is not revocable"); /* uint128 vestedAmount = _computeReleasableAmount(vestingSchedule); if (vestedAmount > 0) { release(vestingScheduleId, vestedAmount); } */ uint256 unreleased = vestingSchedule.amountTotal - vestingSchedule.released; vestingSchedulesTotalAmount = vestingSchedulesTotalAmount - unreleased; vestingSchedule.revoked = true; emit Revoked(msg.sender, vestingSchedule.beneficiary, vestingScheduleId); } /** * @notice Release vested amount of tokens. * @param vestingScheduleId the vesting schedule identifier * @param amount the amount to release */ function release( bytes32 vestingScheduleId, uint128 amount ) public virtual nonReentrant onlyIfVestingScheduleNotRevoked(vestingScheduleId) { VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; bool isBeneficiary = msg.sender == vestingSchedule.beneficiary; bool isOwner = msg.sender == owner(); require( isBeneficiary || isOwner, "TokenVesting: only beneficiary and owner can release vested tokens" ); uint256 vestedAmount = _computeReleasableAmount(vestingSchedule); require(vestedAmount >= amount, "TokenVesting: cannot release tokens, not enough vested tokens"); vestingSchedule.released = vestingSchedule.released + amount; address payable beneficiaryPayable = payable(vestingSchedule.beneficiary); vestingSchedulesTotalAmount = vestingSchedulesTotalAmount - amount; IERC20(_token).safeTransferFrom(_treasury, beneficiaryPayable, amount); emit Released(msg.sender, beneficiaryPayable, vestingScheduleId, amount); } /** * @dev Returns the number of vesting schedules managed by this contract. * @return the number of vesting schedules */ function getVestingSchedulesCount() public view virtual returns (uint256) { return vestingSchedulesIds.length; } /** * @notice Computes the vested amount of tokens for the given vesting schedule identifier. * @return the vested amount */ function computeReleasableAmount( bytes32 vestingScheduleId ) public view virtual onlyIfVestingScheduleExists(vestingScheduleId) returns (uint256) { VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; return _computeReleasableAmount(vestingSchedule); } /** * @notice Returns the vesting schedule information for a given identifier. * @return the vesting schedule structure information */ function getVestingSchedule(bytes32 vestingScheduleId) public view virtual returns (VestingSchedule memory) { return vestingSchedules[vestingScheduleId]; } /** * @dev Computes the next vesting schedule identifier for a given holder address. */ function computeNextVestingScheduleIdForHolder(address holder) public view virtual returns (bytes32) { return computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder]); } /** * @dev Returns the last vesting schedule for a given holder address. */ function getLastVestingScheduleForHolder(address holder) public view virtual returns (VestingSchedule memory) { return vestingSchedules[computeVestingScheduleIdForAddressAndIndex(holder, holdersVestingCount[holder] - 1)]; } /** * @dev Computes the vesting schedule identifier for an address and an index. */ function computeVestingScheduleIdForAddressAndIndex( address holder, uint256 index ) public pure virtual returns (bytes32) { return keccak256(abi.encodePacked(holder, index)); } /** * @dev Computes the releasable amount of tokens for a vesting schedule. * @return the amount of releasable tokens */ function _computeReleasableAmount(VestingSchedule memory vestingSchedule) internal view virtual returns (uint128) { uint256 currentTime = getCurrentTime(); if (currentTime < vestingSchedule.start || vestingSchedule.revoked == true) { return 0; } else if (currentTime < vestingSchedule.cliff) { return vestingSchedule.immediatelyReleasableAmount - vestingSchedule.released; } else if (currentTime >= vestingSchedule.start + vestingSchedule.duration) { return vestingSchedule.amountTotal - vestingSchedule.released; } else { uint256 timeFromCliff = currentTime - vestingSchedule.cliff; uint256 secondsPerSlice = vestingSchedule.slicePeriodSeconds; uint256 vestedSlicePeriods = timeFromCliff / secondsPerSlice; uint256 vestedSeconds = vestedSlicePeriods * secondsPerSlice; uint256 vestedAmount = (vestingSchedule.amountTotal - vestingSchedule.immediatelyReleasableAmount) * vestedSeconds / (vestingSchedule.duration + vestingSchedule.start - vestingSchedule.cliff) + vestingSchedule.immediatelyReleasableAmount - vestingSchedule.released; return uint128(vestedAmount); } } function getCurrentTime() internal virtual view returns (uint256) { return block.timestamp; } /** * @inheritdoc UUPSUpgradeable */ function _authorizeUpgrade(address) internal virtual override onlyOwner {} }
Revokes the vesting schedule for given identifier. vestingScheduleId the vesting schedule identifier/
function revoke( bytes32 vestingScheduleId ) public virtual onlyOwner onlyIfVestingScheduleNotRevoked(vestingScheduleId) { VestingSchedule storage vestingSchedule = vestingSchedules[vestingScheduleId]; require(vestingSchedule.revocable == true, "TokenVesting: vesting is not revocable"); uint128 vestedAmount = _computeReleasableAmount(vestingSchedule); if (vestedAmount > 0) { release(vestingScheduleId, vestedAmount); } vestingSchedulesTotalAmount = vestingSchedulesTotalAmount - unreleased; vestingSchedule.revoked = true; emit Revoked(msg.sender, vestingSchedule.beneficiary, vestingScheduleId); }
7,300,542
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "./interface/ILendingPool.sol"; import "./interface/IDebtToken.sol"; import "./interface/IProtocolDataProvider.sol"; import "./interface/IStrategy.sol"; import "./interface/IAaveOracle.sol"; import "./interface/IDividendRightsToken.sol"; contract DelegateCreditManager is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct DelegatorInfo { uint256 amountDelegated; uint256 amountDeployed; } struct StrategyInfo { address strategyAddress; uint256 amountWorking; } ILendingPool lendingPool; IProtocolDataProvider provider; address public constant oracleAddress = 0x0229F777B0fAb107F9591a41d5F02E4e98dB6f2d; uint256 public constant MAX_REF = 10000; uint256 public constant SAFE_REF = 4500; uint256 public SHARE_DIVISOR = 0.01 ether; mapping(address => mapping(address => DelegatorInfo)) public delegators; mapping(address => StrategyInfo) public strategies; mapping(address => address) public dividends; mapping(address => uint256) public totalDelegatedAmounts; event StrategyAdded( address want, address strategyAddress, uint256 timestamp ); event DividendAdded( address want, address dividendsAddress, uint256 timestamp ); event DeployedDelegatedCapital( address delegator, uint256 amountDeployed, address strategy, uint256 timestamp ); event FreeDelegatedCapital( address delegator, uint256 amountRemoved, address strategy, uint256 timestamp ); constructor(ILendingPool _lendingPool, IProtocolDataProvider _provider) public { lendingPool = _lendingPool; provider = _provider; } /** * @dev Sets the new strategy where funds will be deployed for a specific asset type * @param _asset Asset which the strategy will use for generating $ * @param _strategy The new strategy address **/ function setNewStrategy(address _asset, address _strategy) external onlyOwner { strategies[_asset] = StrategyInfo({ strategyAddress: _strategy, amountWorking: type(uint256).min }); IERC20(_asset).approve(_strategy, type(uint256).max); IERC20(_asset).approve(address(lendingPool), type(uint256).max); emit StrategyAdded(_asset, _strategy, block.timestamp); } /** * @dev Sets the new dividends contract address to mint/burn appropriately * @param _asset Asset which the drt will use as underlying * @param _drt The new dividend address **/ function setNewDividend(address _asset, address _drt) external onlyOwner { dividends[_asset] = _drt; emit DividendAdded(_asset, _drt, block.timestamp); } /** * @dev Allows user to first deposit in Aave and then delegate (point of contact user:protocol) * @param _assetDeposit The asset which is deposited in Aave * @param _assetStrategy The asset used in the strategy * @param _amount The amount deposited in Aave of _assetDeposit type **/ function depositAaveAndDelegate( address _assetDeposit, address _assetStrategy, uint256 _amount ) external { IERC20(_assetDeposit).safeTransferFrom( msg.sender, address(this), _amount ); lendingPool.deposit(_assetDeposit, _amount, msg.sender, 0); (, , uint256 availableBorrowsETH, , , ) = lendingPool .getUserAccountData(msg.sender); uint256 ratioOracle = IAaveOracle(oracleAddress).getAssetPrice( _assetStrategy ); uint256 safeDelegableAmount = availableBorrowsETH .mul(10**18) .mul(SAFE_REF) .div(MAX_REF) .div(ratioOracle); _delegateCreditLine(_assetStrategy, safeDelegableAmount); } /// @dev Allows user to delegate to our protocol (point of contact user:protocol) function delegateCreditLine(address _asset, uint256 _amount) external { _delegateCreditLine(_asset, _amount); } /** * @param _asset The asset which is delegated * @param _amount The amount delegated to us to manage **/ function _delegateCreditLine(address _asset, uint256 _amount) internal { (, , address variableDebtTokenAddress) = provider .getReserveTokensAddresses(_asset); uint256 borrowableAllowance = IDebtToken(variableDebtTokenAddress) .borrowAllowance(msg.sender, address(this)); DelegatorInfo storage delegator = delegators[msg.sender][_asset]; if (borrowableAllowance > 0) { totalDelegatedAmounts[_asset] = totalDelegatedAmounts[_asset].add( borrowableAllowance ); delegator.amountDelegated = delegator.amountDelegated.add( borrowableAllowance ); deployCapital(_asset, msg.sender); } } /// @dev Allows user to remove from protocol delegated funds (point of contact user:protocol) function freeDelegatedCapital(address _asset, uint256 _amount) external { unwindCapital(_asset, msg.sender, _amount); } /** * @param _asset The asset which is going to be remove from strategy * @param _delegator Delegator address, use to update mapping * @param _amount Amount to unwind from our system and repay Aaave **/ function unwindCapital( address _asset, address _delegator, uint256 _amount ) internal { DelegatorInfo storage delegator = delegators[_delegator][_asset]; require(_amount <= delegator.amountDelegated, ">amountDelegated"); StrategyInfo storage strategyInfo = strategies[_asset]; require(strategyInfo.strategyAddress != address(0), "notSetStrategy!"); require(delegator.amountDeployed > 0, "noDeployedCapital!"); delegator.amountDelegated = delegator.amountDelegated.sub(_amount); delegator.amountDeployed = delegator.amountDeployed.sub(_amount); totalDelegatedAmounts[_asset] = totalDelegatedAmounts[_asset].add( _amount ); IStrategy(strategyInfo.strategyAddress).withdraw( address(this), _amount ); uint256 repayableAmount = Math.min( _amount, IERC20(_asset).balanceOf(address(this)) ); lendingPool.repay(_asset, repayableAmount, 2, _delegator); address dividendsTokenAddress = dividends[_asset]; require(dividendsTokenAddress != address(0), "notSetDividend!"); IDividendRightsToken(dividendsTokenAddress).burn( _delegator, repayableAmount.div(SHARE_DIVISOR) ); emit FreeDelegatedCapital( _delegator, repayableAmount, strategyInfo.strategyAddress, block.timestamp ); } /** * @dev Deploys the new delegated inmediatly into the strategy * @param _asset The asset which is going to be deployed * @param _delegator Delegator address, use to update mapping **/ function deployCapital(address _asset, address _delegator) internal { StrategyInfo storage strategyInfo = strategies[_asset]; require(strategyInfo.strategyAddress != address(0), "notSetStrategy!"); DelegatorInfo storage delegator = delegators[_delegator][_asset]; if (delegator.amountDelegated >= delegator.amountDeployed) { uint256 amountToBorrow = delegator.amountDelegated.sub( delegator.amountDeployed ); require(amountToBorrow > 0, "0!"); lendingPool.borrow(_asset, amountToBorrow, 2, 0, _delegator); delegator.amountDeployed = delegator.amountDeployed.add( amountToBorrow ); IStrategy(strategyInfo.strategyAddress).deposit(amountToBorrow); strategyInfo.amountWorking = strategyInfo.amountWorking.add( amountToBorrow ); address dividendsTokenAddress = dividends[_asset]; require(dividendsTokenAddress != address(0), "notSetDividend!"); IDividendRightsToken(dividendsTokenAddress).issue( _delegator, amountToBorrow.div(SHARE_DIVISOR) ); emit DeployedDelegatedCapital( _delegator, amountToBorrow, strategyInfo.strategyAddress, block.timestamp ); } } }
Deploys the new delegated inmediatly into the strategy _asset The asset which is going to be deployed _delegator Delegator address, use to update mapping/
function deployCapital(address _asset, address _delegator) internal { StrategyInfo storage strategyInfo = strategies[_asset]; require(strategyInfo.strategyAddress != address(0), "notSetStrategy!"); DelegatorInfo storage delegator = delegators[_delegator][_asset]; if (delegator.amountDelegated >= delegator.amountDeployed) { uint256 amountToBorrow = delegator.amountDelegated.sub( delegator.amountDeployed ); require(amountToBorrow > 0, "0!"); lendingPool.borrow(_asset, amountToBorrow, 2, 0, _delegator); delegator.amountDeployed = delegator.amountDeployed.add( amountToBorrow ); IStrategy(strategyInfo.strategyAddress).deposit(amountToBorrow); strategyInfo.amountWorking = strategyInfo.amountWorking.add( amountToBorrow ); address dividendsTokenAddress = dividends[_asset]; require(dividendsTokenAddress != address(0), "notSetDividend!"); IDividendRightsToken(dividendsTokenAddress).issue( _delegator, amountToBorrow.div(SHARE_DIVISOR) ); emit DeployedDelegatedCapital( _delegator, amountToBorrow, strategyInfo.strategyAddress, block.timestamp ); } }
13,120,828
./full_match/44787/0x612e95C6509bB95fb50e0721D64CDdF732e58Dc5/sources/contracts/community/CommunityAdminImplementation.sol
Adds a new manager to a community _community address of the community _account address to be added as community manager/
function addManagerToCommunity(ICommunity _community, address _account) external override onlyOwner { _community.addManager(_account); }
13,266,303
/** *Submitted for verification at Etherscan.io on 2020-07-14 */ /** *Submitted for verification at Etherscan.io on 2019-10-02 */ pragma solidity ^0.5.8; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { bool private stopped; address public _owner; address public _admin; address private proposedOwner; mapping(address => bool) private _allowed; event Stopped(); event Started(); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Allowed(address indexed _address); event RemoveAllowed(address indexed _address); constructor () internal { stopped = false; _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } modifier onlyAllowed() { require(isAllowed() || isOwner()); _; } modifier onlyWhenNotStopped() { require(!isStopped()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function isAllowed() public view returns (bool) { return _allowed[msg.sender]; } function allow(address _target) external onlyOwner returns (bool) { _allowed[_target] = true; emit Allowed(_target); return true; } function removeAllowed(address _target) external onlyOwner returns (bool) { _allowed[_target] = false; emit RemoveAllowed(_target); return true; } function isStopped() public view returns (bool) { if(isOwner() || isAllowed()) { return false; } else { return stopped; } } function stop() public onlyOwner { _stop(); } function start() public onlyOwner { _start(); } function proposeOwner(address _proposedOwner) public onlyOwner { require(msg.sender != _proposedOwner); proposedOwner = _proposedOwner; } function claimOwnership() public { require(msg.sender == proposedOwner); emit OwnershipTransferred(_owner, proposedOwner); _owner = proposedOwner; proposedOwner = address(0); } function _stop() internal { emit Stopped(); stopped = true; } function _start() internal { emit Started(); stopped = false; } } contract BaseToken is Ownable { using SafeMath for uint256; uint256 constant internal E18 = 1000000000000000000; uint256 constant public decimals = 18; uint256 public totalSupply; struct Lock { uint256 amount; uint256 expiresAt; } mapping (address => uint256) public balances; mapping (address => mapping ( address => uint256 )) public approvals; mapping (address => Lock[]) public lockup; mapping(address => bool) public lockedAddresses; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Locked(address _who,uint256 _index); event UnlockedAll(address _who); event UnlockedIndex(address _who, uint256 _index); event Burn(address indexed from, uint256 indexed value); constructor() public { balances[msg.sender] = totalSupply; } modifier transferParamsValidation(address _from, address _to, uint256 _value) { require(_from != address(0)); require(_to != address(0)); require(_value > 0); require(balances[_from] >= _value); require(!isLocked(_from, _value)); _; } modifier canTransfer(address _sender, uint256 _value) { require(!lockedAddresses[_sender]); require(_sender != address(0)); _; } function balanceOf(address _who) view public returns (uint256) { return balances[_who]; } function lockedBalanceOf(address _who) view public returns (uint256) { require(_who != address(0)); uint256 lockedBalance ; //inject UNINIT LOCAL/STATE VAR if(lockup[_who].length > 0) { Lock[] storage locks = lockup[_who]; uint256 length ; //inject UNINIT LOCAL/STATE VAR for (uint i ; i < length; i++) //inject UNINIT LOCAL/STATE VAR { if (now < locks[i].expiresAt) { lockedBalance = lockedBalance.add(locks[i].amount); } } } return lockedBalance; } function allowance(address _owner, address _spender) view external returns (uint256) { return approvals[_owner][_spender]; } function isLocked(address _who, uint256 _value) view public returns(bool) { uint256 lockedBalance ; //inject UNINIT LOCAL/STATE VAR uint256 balance ; //inject UNINIT LOCAL/STATE VAR if(lockedBalance <= 0) { return false; } else { return !(balance > lockedBalance && balance.sub(lockedBalance) >= _value); } } function transfer(address _to, uint256 _value) external onlyWhenNotStopped canTransfer(msg.sender, _value) transferParamsValidation(msg.sender, _to, _value) returns (bool) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) external onlyWhenNotStopped transferParamsValidation(_from, _to, _value) returns (bool) { require(approvals[_from][msg.sender] >= _value); approvals[_from][msg.sender] = approvals[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } // transferWithLock is only for airdrop or marketing purpose function transferWithLock(address _to, uint256 _value, uint256 _time) onlyOwner transferParamsValidation(msg.sender, _to, _value) external returns (bool) { require(_time > now); _lock(_to, _value, _time); _transfer(msg.sender, _to, _value); return true; } // lockAddress is only for security accident prevention function lockAddress(address _addr, bool _locked) onlyOwner external { lockedAddresses[_addr] = _locked; } // approve is for transfer authentication function approve(address _spender, uint256 _value) external onlyWhenNotStopped returns (bool) { require(_spender != address(0)); require(balances[msg.sender] >= _value); require(msg.sender != _spender); approvals[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function unlock(address _who, uint256 _index) onlyOwner external returns (bool) { uint256 length ; //inject UNINIT LOCAL/STATE VAR require(length > _index); lockup[_who][_index] = lockup[_who][length - 1]; lockup[_who].length--; emit UnlockedIndex(_who, _index); return true; } function unlockAll(address _who) onlyOwner external returns (bool) { require(lockup[_who].length > 0); delete lockup[_who]; emit UnlockedAll(_who); return true; } // burn is for incubator fund or security accident prevention function burn(uint256 _value) external { require(balances[msg.sender] >= _value); require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); } function _mint(address account, uint256 _value) internal { require(account != address(0)); totalSupply = totalSupply.add(_value); balances[account] = balances[account].add(_value); emit Transfer(address(0), account, _value); } function _transfer(address _from, address _to, uint256 _value) internal { balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); } function _lock(address _who, uint256 _value, uint256 _dateTime) onlyOwner internal { lockup[_who].push(Lock(_value, _dateTime)); emit Locked(_who, lockup[_who].length - 1); } // destruction is for token upgrade function destruction() onlyOwner public { selfdestruct(msg.sender); } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is BaseToken, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ // mint is only for THENODE's daily MPoS mining (250000 THE) function mint(address to, uint256 value) public onlyMinter returns (bool) { _mint(to, value); return true; } } contract THECASH is BaseToken, ERC20Mintable { using SafeMath for uint256; string constant public name = 'THECASH'; string constant public symbol = 'TCH'; string constant public version = '1.0.0'; constructor() public { totalSupply = 2000000 * E18; balances[msg.sender] = totalSupply; } }
approve is for transfer authentication
function approve(address _spender, uint256 _value) external onlyWhenNotStopped returns (bool) { require(_spender != address(0)); require(balances[msg.sender] >= _value); require(msg.sender != _spender); approvals[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
12,651,215
./full_match/1/0x500Dd74CdeAaDd09F689E8fC42Bf8e5D3a6A7a1C/sources/contracts/StrategyConvexStables.sol
Specify tokens used in yield process, should not be available to withdraw via withdrawOther()
function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() public view virtual returns (address[] memory) { return new address[](0); }
2,998,311
/** *Submitted for verification at Etherscan.io on 2021-07-28 */ // File: @openzeppelin/upgrades/contracts/Initializable.sol pragma solidity 0.5.1; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the 'initializer' modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.1; /** * @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/drafts/Counters.sol pragma solidity 0.5.1; /** * @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-ethereum-package/contracts/GSN/Context.sol pragma solidity 0.5.1; /* * @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 is Initializable { // 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-ethereum-package/contracts/introspection/IERC165.sol pragma solidity 0.5.1; /** * @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-ethereum-package/contracts/token/ERC721/IERC721.sol pragma solidity 0.5.1; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is Initializable, 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-ethereum-package/contracts/token/ERC721/IERC721Receiver.sol pragma solidity 0.5.1; /** * @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-ethereum-package/contracts/math/SafeMath.sol // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity 0.5.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 * ==== */ 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-ethereum-package/contracts/drafts/Counters.sol // File: @openzeppelin/contracts-ethereum-package/contracts/introspection/ERC165.sol pragma solidity 0.5.1; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is Initializable, 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; function initialize() public initializer { // 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 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; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol pragma solidity 0.5.1; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Initializable, 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; function initialize() public initializer { ERC165.initialize(); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_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 _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) 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); } } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity 0.5.1; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is Initializable, 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-ethereum-package/contracts/token/ERC721/ERC721Enumerable.sol pragma solidity 0.5.1; /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Initializable, 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. */ function initialize() public initializer { require(ERC721._hasBeenInitialized()); // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_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; } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721Metadata.sol pragma solidity 0.5.1; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is Initializable, IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Metadata.sol pragma solidity 0.5.1; contract ERC721Metadata is Initializable, Context, ERC165, ERC721, IERC721Metadata { // 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('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ function initialize(string memory name, string memory symbol) public initializer { require(ERC721._hasBeenInitialized()); _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function _hasBeenInitialized() internal view returns (bool) { return supportsInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * 'http://api.myproject.com/token/<id>'), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { 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}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @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]; } } uint256[49] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Full.sol pragma solidity 0.5.1; /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is Initializable, ERC721, ERC721Enumerable, ERC721Metadata { uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol pragma solidity 0.5.1; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol pragma solidity 0.5.1; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Mintable.sol pragma solidity 0.5.1; /** * @title ERC721Mintable * @dev ERC721 minting logic. */ contract ERC721Mintable is Initializable, ERC721, MinterRole { function initialize(address sender) public initializer { require(ERC721._hasBeenInitialized()); MinterRole.initialize(sender); } /** * @dev Function to mint tokens. * @param to The address that will receive the minted token. * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 tokenId) public onlyMinter returns (bool) { _mint(to, tokenId); return true; } /** * @dev Function to safely mint tokens. * @param to The address that will receive the minted token. * @param tokenId The token id to mint. * @return A boolean that indicates if the operation was successful. */ function safeMint(address to, uint256 tokenId) public onlyMinter returns (bool) { _safeMint(to, tokenId); return true; } /** * @dev Function to safely mint tokens. * @param to The address that will receive the minted token. * @param tokenId The token id to mint. * @param _data bytes data to send along with a safe transfer check. * @return A boolean that indicates if the operation was successful. */ function safeMint(address to, uint256 tokenId, bytes memory _data) public onlyMinter returns (bool) { _safeMint(to, tokenId, _data); return true; } uint256[50] private ______gap; } // File: contracts/fantoken.sol pragma solidity 0.5.1; contract NFTImplementation is Initializable, ERC721Full, ERC721Mintable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; address private owner; modifier onlyOwner { require(msg.sender == owner, "Not allowed to call this method"); _; } function initialize(string memory name, string memory symbol, address sender) public initializer { ERC721.initialize(); ERC721Metadata.initialize(name, symbol); ERC721Enumerable.initialize(); ERC721Mintable.initialize(sender); owner = msg.sender; } function getOwner() public view returns (address) { return owner; } function mint(address to, uint256 tokenId) public onlyOwner returns (bool) { _mint(to, tokenId); return true; } /** * @dev Minting a single token to an address. Can be called by a minter only * @param to Address which will receive the token * @param tokenURI The metadata URI for the new minted token */ function mintSingle(address to, string memory tokenURI) onlyMinter public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(to, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; } /** * @dev Transfers multiple tokens to a list of addresses. * The msg.sender must own all the tokens to be transferred. * @param to Addresses which will receive the tokens, one per address * @param tokenIds List of token IDs to be transferred */ function transferMultiple(address[] calldata to, uint256[] calldata tokenIds) external { bool isOwner = _isOwnerForAll(msg.sender, tokenIds); require(isOwner == true, "not owner of all these tokens"); uint256 count = tokenIds.length; for (uint256 index = 0; index < count; index++) { safeTransferFrom(msg.sender, to[index], tokenIds[index]); } } /** * @dev Verifies if an address owns all the tokens in the list. * @param _owner Address which will be verified as owner of the tokens * @param _tokenIds List of tokens */ function _isOwnerForAll(address _owner, uint256[] memory _tokenIds) private returns (bool) { uint256 count = _tokenIds.length; address _tokenOwner; for (uint256 index = 0; index < count; index++) { _tokenOwner = ownerOf(_tokenIds[index]); if(_tokenOwner != _owner) { return false; } } return true; } /** * @dev Minting a specific number of tokens to an address. Can be called by a minter only * @param to Address which will receive the token * @param tokenURI The metadata URI, without token ID, for the new minted tokens * @param total Number of tokens to be minted */ function mintMultiple(address to, string calldata tokenURI, uint256 total) external onlyMinter returns (uint256[] memory) { uint256[] memory _minted = new uint256[](total); uint256 _tokenId; uint256 newItemId; for (uint256 i = 0; i < total; i++) { _minted[i] = _mintSingle(to, tokenURI); } return _minted; } /** * @dev Minting a tokens to a list of addresses. Can be called by a minter only * @param to List of addresses which will receive the tokens * @param tokenURI The metadata URI, without token ID, for the new minted tokens */ function mintMultiple(address[] calldata to, string calldata tokenURI) external onlyMinter returns (uint256[] memory) { uint256 total = to.length; uint256[] memory _minted = new uint256[](total); uint256 _tokenId; uint256 newItemId; for (uint256 i = 0; i < total; i++) { _minted[i] = _mintSingle(to[i], tokenURI); } return _minted; } /** * @dev Minting one token to an address * @param _to Address which will receive the token * @param _tokenUri The metadata URI, without token ID, for the new minted token */ function _mintSingle(address _to, string memory _tokenUri) private returns (uint256 _tid) { uint256 _tid; string memory concatUrl; _tokenIds.increment(); _tid = _tokenIds.current(); _mint(_to, _tid); concatUrl = concatStringDec(_tokenUri, _tid); _setTokenURI(_tid, concatUrl); return _tid; } /** * @dev Removes a minter from minters list. * Can be called only by the smart contract owner. * @param minter Address to be removed */ function removeMinter(address minter) onlyOwner external { if(!isMinter(minter)) { return; } _removeMinter(minter); } /** * @dev Burns a token * Can be called only by the smart contract owner. * @param tokenId ID of the token to be burnt */ function burn( uint256 tokenId) public onlyOwner { super._burn(tokenId); } /** * @dev Appends an integer to a string * @param s String to be processed * @param x Integer to be appended */ function concatStringDec(string memory s, uint256 x) private pure returns (string memory) { return string(abi.encodePacked(s, itod(x))); } function itod(uint256 x) private pure returns (string memory) { if (x > 0) { string memory str; while (x > 0) { str = string(abi.encodePacked(uint8(x % 10 + 48), str)); x /= 10; } return str; } return "0"; } }
Verifies if an address owns all the tokens in the list. _owner Address which will be verified as owner of the tokens _tokenIds List of tokens/
function _isOwnerForAll(address _owner, uint256[] memory _tokenIds) private returns (bool) { uint256 count = _tokenIds.length; address _tokenOwner; for (uint256 index = 0; index < count; index++) { _tokenOwner = ownerOf(_tokenIds[index]); if(_tokenOwner != _owner) { return false; } } return true; }
6,494,215
pragma solidity ^0.5.8; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./SortedFractionMedianList.sol"; import "./interfaces/ISortedOracles.sol"; import "../common/Initializable.sol"; /** * @title Maintains a sorted list of oracle exchange rates between Celo Gold and other currencies. */ contract SortedOracles is ISortedOracles, Ownable, Initializable { using SafeMath for uint256; using SafeMath for uint128; using SortedFractionMedianList for SortedFractionMedianList.List; // Maps a token address to a sorted list of oracle values. mapping(address => SortedFractionMedianList.List) public rates; // TODO(asa): This doesn't need to be a list of fractions. mapping(address => SortedFractionMedianList.List) public timestamps; mapping(address => mapping(address => bool)) public isOracle; mapping(address => address[]) public oracles; uint256 public reportExpirySeconds; event OracleAdded( address indexed token, address indexed oracleAddress ); event OracleRemoved( address indexed token, address indexed oracleAddress ); event OracleReported( address token, address oracle, uint256 timestamp, uint128 numerator, uint128 denominator ); event OracleReportRemoved( address indexed token, address indexed oracle ); event MedianUpdated( address token, uint128 numerator, uint128 denominator ); event ReportExpirySet( uint256 reportExpiry ); modifier onlyOracle(address token) { require(isOracle[token][msg.sender], "sender was not an oracle for token addr"); _; } function initialize(uint256 _reportExpirySeconds) external initializer { _transferOwnership(msg.sender); reportExpirySeconds = _reportExpirySeconds; } /** * @notice Sets the report expiry parameter. * @param _reportExpirySeconds Desired value of report expiry. */ function setReportExpiry(uint256 _reportExpirySeconds) external onlyOwner { reportExpirySeconds = _reportExpirySeconds; emit ReportExpirySet(_reportExpirySeconds); } /** * @notice Adds a new Oracle. * @param token The address of the token. * @param oracleAddress The address of the oracle. */ function addOracle(address token, address oracleAddress) external onlyOwner { require( token != address(0) && oracleAddress != address(0) && !isOracle[token][oracleAddress], "token addr was null or oracle addr was null or oracle addr is not an oracle for token addr" ); isOracle[token][oracleAddress] = true; oracles[token].push(oracleAddress); emit OracleAdded(token, oracleAddress); } /** * @notice Removes an Oracle. * @param oracleAddress The address of the oracle. */ function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner { require( token != address(0) && oracleAddress != address(0) && oracles[token].length > index && oracles[token][index] == oracleAddress, "token addr null or oracle addr null or index of token oracle not mapped to oracle addr" ); isOracle[token][oracleAddress] = false; oracles[token][index] = oracles[token][oracles[token].length.sub(1)]; oracles[token].length = oracles[token].length.sub(1); if (reportExists(token, oracleAddress)) { removeReport(token, oracleAddress); } emit OracleRemoved(token, oracleAddress); } /** * @notice Removes a report that is expired. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @param n The number of expired reports to remove, at most (deterministic upper gas bound). */ function removeExpiredReports(address token, uint256 n) external { require( token != address(0) && timestamps[token].tail != address(0) && n < timestamps[token].numElements ); for (uint256 i = 0; i < n; i++) { address oldest = timestamps[token].tail; uint128 timestamp = timestamps[token].elements[oldest].numerator; // solhint-disable-next-line not-rely-on-time if (uint128(now).sub(timestamp) >= uint128(reportExpirySeconds)) { removeReport(token, oldest); } else { break; } } } /** * @notice Updates an oracle value and the median. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @param numerator The amount of tokens equal to `denominator` Celo Gold. * @param denominator The amount of Celo Gold equal to `numerator` tokens. * @param lesserKey The element which should be just left of the new oracle value. * @param greaterKey The element which should be just right of the new oracle value. * @dev Values are passed as uint128 to avoid uint256 overflow when multiplying. * @dev Note that only one of `lesserKey` or `greaterKey` needs to be correct to reduce friction. */ function report( address token, uint128 numerator, uint128 denominator, address lesserKey, address greaterKey ) external onlyOracle(token) { SortedFractionMedianList.Element memory originalMedian = getMedianElement(rates[token]); rates[token].insertOrUpdate(msg.sender, numerator, denominator, lesserKey, greaterKey); timestamps[token].insertOrUpdate( msg.sender, // solhint-disable-next-line not-rely-on-time uint128(now), 1, getLesserTimestampKey(token, msg.sender), address(0) ); // solhint-disable-next-line not-rely-on-time emit OracleReported(token, msg.sender, now, numerator, denominator); emitIfMedianUpdated(token, originalMedian); } /** * @notice Returns the number of rates. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return The number of reported oracle rates for `token`. */ function numRates(address token) external view returns (uint256) { return rates[token].numElements; } /** * @notice Returns the median rate. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return The median exchange rate for `token`. */ function medianRate(address token) external view returns (uint128, uint128) { SortedFractionMedianList.Element memory median = getMedianElement(rates[token]); return (median.numerator, median.denominator); } /** * @notice Gets all elements from the doubly linked list. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return An unpacked list of elements from largest to smallest. */ function getRates( address token ) external view returns ( address[] memory, uint256[] memory, uint256[] memory, SortedFractionMedianList.MedianRelation[] memory ) { return rates[token].getElements(); } /** * @notice Returns the number of timestamps. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return The number of oracle report timestamps for `token`. */ function numTimestamps(address token) external view returns (uint256) { return timestamps[token].numElements; } /** * @notice Returns the median timestamp. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return The median report timestamp for `token`. */ function medianTimestamp(address token) external view returns (uint128) { return getMedianElement(timestamps[token]).numerator; } /** * @notice Gets all elements from the doubly linked list. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @return An unpacked list of elements from largest to smallest. */ function getTimestamps( address token ) external view returns ( address[] memory, uint256[] memory, uint256[] memory, SortedFractionMedianList.MedianRelation[] memory ) { return timestamps[token].getElements(); } /** * @notice Returns whether a report exists on token from oracle. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @param oracle The oracle whose report should be checked. */ function reportExists(address token, address oracle) internal view returns (bool) { return rates[token].elements[oracle].denominator != 0 && timestamps[token].elements[oracle].denominator != 0; } /** * @notice Returns the median element. * @return The median element. */ function getMedianElement( SortedFractionMedianList.List storage list ) private view returns (SortedFractionMedianList.Element memory) { return list.elements[list.medianKey]; } /** * @notice Removes an oracle value and updates the median. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @param oracle The oracle whose value should be removed. * @dev This can be used to delete elements for oracles that have been removed. */ function removeReport(address token, address oracle) private { SortedFractionMedianList.Element memory originalMedian = getMedianElement(rates[token]); rates[token].remove(oracle); timestamps[token].remove(oracle); emit OracleReportRemoved(token, oracle); emitIfMedianUpdated(token, originalMedian); } /** * @notice Emits the MedianUpdated event if the median rate has changed. * @param token The address of the token for which the median rate may have changed. * @param originalMedian The original median rate. */ function emitIfMedianUpdated( address token, SortedFractionMedianList.Element memory originalMedian ) private { SortedFractionMedianList.Element memory newMedian = getMedianElement(rates[token]); if ( originalMedian.numerator != newMedian.numerator || originalMedian.denominator != newMedian.denominator ) { emit MedianUpdated( token, newMedian.numerator, newMedian.denominator ); } } /** * @notice Returns the key for the lesser element in the timestamp list. * @param token The address of the token for which the Celo Gold exchange rate is being reported. * @param oracle The address of the oracle to sort into the timestamp list. * @return The key of the lesser element in the list. */ function getLesserTimestampKey(address token, address oracle) private view returns(address) { address head = timestamps[token].head; if (head == oracle) { return timestamps[token].elements[head].lesserKey; } else { return head; } } }
Removes an Oracle. oracleAddress The address of the oracle./
function removeOracle(address token, address oracleAddress, uint256 index) external onlyOwner { require( token != address(0) && oracleAddress != address(0) && oracles[token].length > index && oracles[token][index] == oracleAddress, "token addr null or oracle addr null or index of token oracle not mapped to oracle addr" ); isOracle[token][oracleAddress] = false; oracles[token][index] = oracles[token][oracles[token].length.sub(1)]; oracles[token].length = oracles[token].length.sub(1); if (reportExists(token, oracleAddress)) { removeReport(token, oracleAddress); } emit OracleRemoved(token, oracleAddress); }
916,617
./full_match/1/0x666E6748db572ebC3AE40e4Ce7748bC9bE7A5AAe/sources/Users/kstasi/Documents/side/dANT/contracts/Rewards.sol
Returns claimed and unclaimed user's reward. _user Address of the user. return _reward User's reward.
function getReward(address _user) public virtual view returns (uint256 _reward) { UserInfo storage user = userInfo[_user]; _reward = user.reward; for (uint256 i = user.depositHead; i < user.depositTail; i++) { DepositInfo memory deposit = user.deposits[i]; _reward = _reward.add( Math .min(now, deposit.time) .sub(user.lastUpdate) .mul(deposit.amount) .mul(rewardPerSec) .div(1e18) ); } }
4,935,877
./full_match/122/0xFAE02d404c327A1Eb2fB38eb89C38860a02D70e6/sources/contracts/LiquidStakingPool.sol
Sets the validator index of the protocol _index the value to set the current index to/
function _setValidatorIndex(uint256 _index) internal { _validatorsIndex = _index; }
16,366,203
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface ICurveGaugeMapping { struct GaugeData { address gaugeAddress; bool rewardToken; } function GAUGEMAPPING439(bytes32) external view returns(GaugeData memory); //inject NONSTANDARD NAMING } interface TokenInterface { function BALANCEOF742(address) external view returns (uint); //inject NONSTANDARD NAMING } interface IMintor { function MINTED437(address) external view returns (uint); //inject NONSTANDARD NAMING } interface IGauge { function INTEGRATE_FRACTION856(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function LP_TOKEN427() external view returns(address token); //inject NONSTANDARD NAMING function REWARDED_TOKEN28() external view returns(address token); //inject NONSTANDARD NAMING function CRV_TOKEN827() external view returns(address token); //inject NONSTANDARD NAMING function BALANCEOF742(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function REWARDS_FOR32(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING function CLAIMED_REWARDS_FOR119(address user) external view returns(uint256 amt); //inject NONSTANDARD NAMING } contract GaugeHelper { function GETCURVEGAUGEMAPPINGADDR166() internal pure returns (address){ //inject NONSTANDARD NAMING return 0x1C800eF1bBfE3b458969226A96c56B92a069Cc92; } function GETCURVEMINTORADDR2() internal pure returns (address){ //inject NONSTANDARD NAMING return 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; } function STRINGTOBYTES32152(string memory str) internal pure returns (bytes32 result) { //inject NONSTANDARD NAMING require(bytes(str).length != 0, "string-empty"); // solium-disable-next-line security/no-inline-assembly assembly { result := mload(add(str, 32)) } } } contract Resolver is GaugeHelper { struct PositionData { uint stakedBal; uint crvEarned; uint crvClaimed; uint rewardsEarned; uint rewardsClaimed; uint crvBal; uint rewardBal; bool hasReward; } function GETPOSITION539(string memory gaugeName, address user) public view returns (PositionData memory positionData) { //inject NONSTANDARD NAMING ICurveGaugeMapping curveGaugeMapping = ICurveGaugeMapping(GETCURVEGAUGEMAPPINGADDR166()); ICurveGaugeMapping.GaugeData memory curveGaugeData = curveGaugeMapping.GAUGEMAPPING439( bytes32(STRINGTOBYTES32152(gaugeName) )); IGauge gauge = IGauge(curveGaugeData.gaugeAddress); IMintor mintor = IMintor(GETCURVEMINTORADDR2()); positionData.stakedBal = gauge.BALANCEOF742(user); positionData.crvEarned = gauge.INTEGRATE_FRACTION856(user); positionData.crvClaimed = mintor.MINTED437(user); if (curveGaugeData.rewardToken) { positionData.rewardsEarned = gauge.REWARDS_FOR32(user); positionData.rewardsClaimed = gauge.CLAIMED_REWARDS_FOR119(user); positionData.rewardBal = TokenInterface(address(gauge.REWARDED_TOKEN28())).BALANCEOF742(user); } positionData.crvBal = TokenInterface(address(gauge.CRV_TOKEN827())).BALANCEOF742(user); } function GETPOSITIONS560(string[] memory gaugesName, address user) public view returns (PositionData[] memory positions) { //inject NONSTANDARD NAMING positions = new PositionData[](gaugesName.length); for (uint i = 0; i < gaugesName.length; i++) { positions[i] = GETPOSITION539(gaugesName[i], user); } } } contract InstaCurveGaugeResolver is Resolver { string public constant name548 = "Curve-Gauge-Resolver-v1"; //inject NONSTANDARD NAMING }
inject NONSTANDARD NAMING
function GETCURVEMINTORADDR2() internal pure returns (address){
1,074,621
./full_match/137/0x1EE74Ae391C6cA3395Af47d57a36aFC42A507F9F/sources/project_/FanPass.sol
Override _baseURI function to return your base URI
function _baseURI() internal view virtual override returns (string memory) { return tokenData.baseTokenURI; }
4,698,030
pragma solidity ^0.4.24; /** * @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) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev 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); uint256 c = _a - _b; return c; } /** * @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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } /* solium-disable security/no-block-members */ /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param _token ERC20 token which is being vested */ function release(ERC20 _token) public { uint256 unreleased = releasableAmount(_token); require(unreleased > 0); released[_token] = released[_token].add(unreleased); _token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param _token ERC20 token which is being vested */ function revoke(ERC20 _token) public onlyOwner { require(revocable); require(!revoked[_token]); uint256 balance = _token.balanceOf(address(this)); uint256 unreleased = releasableAmount(_token); uint256 refund = balance.sub(unreleased); revoked[_token] = true; _token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn&#39;t been released yet. * @param _token ERC20 token which is being vested */ function releasableAmount(ERC20 _token) public view returns (uint256) { return vestedAmount(_token).sub(released[_token]); } /** * @dev Calculates the amount that has already vested. * @param _token ERC20 token which is being vested */ function vestedAmount(ERC20 _token) public view returns (uint256) { uint256 currentBalance = _token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[_token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[_token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } }
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; }
2,059,333
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: contracts/Pausable.sol pragma solidity 0.6.12; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * */ contract Pausable is Context { event Paused(address account); event Shutdown(address account); event Unpaused(address account); event Open(address account); bool public paused; bool public stopEverything; modifier whenNotPaused() { require(!paused, "Pausable: paused"); _; } modifier whenPaused() { require(paused, "Pausable: not paused"); _; } modifier whenNotShutdown() { require(!stopEverything, "Pausable: shutdown"); _; } modifier whenShutdown() { require(stopEverything, "Pausable: not shutdown"); _; } /// @dev Pause contract operations, if contract is not paused. function _pause() internal virtual whenNotPaused { paused = true; emit Paused(_msgSender()); } /// @dev Unpause contract operations, allow only if contract is paused and not shutdown. function _unpause() internal virtual whenPaused whenNotShutdown { paused = false; emit Unpaused(_msgSender()); } /// @dev Shutdown contract operations, if not already shutdown. function _shutdown() internal virtual whenNotShutdown { stopEverything = true; paused = true; emit Shutdown(_msgSender()); } /// @dev Open contract operations, if contract is in shutdown state function _open() internal virtual whenShutdown { stopEverything = false; emit Open(_msgSender()); } } // File: contracts/interfaces/vesper/IController.sol pragma solidity 0.6.12; interface IController { function aaveReferralCode() external view returns (uint16); function feeCollector(address) external view returns (address); function founderFee() external view returns (uint256); function founderVault() external view returns (address); function interestFee(address) external view returns (uint256); function isPool(address) external view returns (bool); function pools() external view returns (address); function strategy(address) external view returns (address); function rebalanceFriction(address) external view returns (uint256); function poolRewards(address) external view returns (address); function treasuryPool() external view returns (address); function uniswapRouter() external view returns (address); function withdrawFee(address) external view returns (uint256); } // File: contracts/interfaces/vesper/IVesperPool.sol pragma solidity 0.6.12; interface IVesperPool is IERC20 { function approveToken() external; function deposit() external payable; function deposit(uint256) external; function multiTransfer(uint256[] memory) external returns (bool); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function rebalance() external; function resetApproval() external; function sweepErc20(address) external; function withdraw(uint256) external; function withdrawETH(uint256) external; function withdrawByStrategy(uint256) external; function feeCollector() external view returns (address); function getPricePerShare() external view returns (uint256); function token() external view returns (address); function tokensHere() external view returns (uint256); function totalValue() external view returns (uint256); function withdrawFee() external view returns (uint256); } // File: contracts/interfaces/vesper/IPoolRewards.sol pragma solidity 0.6.12; interface IPoolRewards { function notifyRewardAmount(uint256) external; function claimReward(address) external; function updateReward(address) external; function rewardForDuration() external view returns (uint256); function claimable(address) external view returns (uint256); function pool() external view returns (address); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); } // File: sol-address-list/contracts/interfaces/IAddressList.sol pragma solidity ^0.6.6; interface IAddressList { event AddressUpdated(address indexed a, address indexed sender); event AddressRemoved(address indexed a, address indexed sender); function add(address a) external returns (bool); function addValue(address a, uint256 v) external returns (bool); function addMulti(address[] calldata addrs) external returns (uint256); function addValueMulti(address[] calldata addrs, uint256[] calldata values) external returns (uint256); function remove(address a) external returns (bool); function removeMulti(address[] calldata addrs) external returns (uint256); function get(address a) external view returns (uint256); function contains(address a) external view returns (bool); function at(uint256 index) external view returns (address, uint256); function length() external view returns (uint256); } // File: sol-address-list/contracts/interfaces/IAddressListExt.sol pragma solidity ^0.6.6; interface IAddressListExt is IAddressList { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // File: sol-address-list/contracts/interfaces/IAddressListFactory.sol pragma solidity ^0.6.6; interface IAddressListFactory { event ListCreated(address indexed _sender, address indexed _newList); function ours(address a) external view returns (bool); function listCount() external view returns (uint256); function listAt(uint256 idx) external view returns (address); function createList() external returns (address listaddr); } // File: contracts/pools/PoolShareToken.sol pragma solidity 0.6.12; /// @title Holding pool share token // solhint-disable no-empty-blocks abstract contract PoolShareToken is ERC20, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable token; IAddressListExt public immutable feeWhiteList; IController public immutable controller; /// @dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); /// @dev The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); bytes32 public immutable domainSeparator; uint256 internal constant MAX_UINT_VALUE = uint256(-1); mapping(address => uint256) public nonces; event Deposit(address indexed owner, uint256 shares, uint256 amount); event Withdraw(address indexed owner, uint256 shares, uint256 amount); constructor( string memory _name, string memory _symbol, address _token, address _controller ) public ERC20(_name, _symbol) { uint256 chainId; assembly { chainId := chainid() } token = IERC20(_token); controller = IController(_controller); IAddressListFactory factory = IAddressListFactory(0xD57b41649f822C51a73C44Ba0B3da4A880aF0029); IAddressListExt _feeWhiteList = IAddressListExt(factory.createList()); _feeWhiteList.grantRole(keccak256("LIST_ADMIN"), _controller); feeWhiteList = _feeWhiteList; domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(_name)), keccak256(bytes("1")), chainId, address(this) ) ); } /** * @notice Deposit ERC20 tokens and receive pool shares depending on the current share price. * @param amount ERC20 token amount. */ function deposit(uint256 amount) external virtual nonReentrant whenNotPaused { _deposit(amount); } /** * @notice Deposit ERC20 tokens with permit aka gasless approval. * @param amount ERC20 token amount. * @param deadline The time at which signature will expire * @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 virtual nonReentrant whenNotPaused { IVesperPool(address(token)).permit(_msgSender(), address(this), amount, deadline, v, r, s); _deposit(amount); } /** * @notice Withdraw collateral based on given shares and the current share price. * Transfer earned rewards to caller. Withdraw fee, if any, will be deduced from * given shares and transferred to feeCollector. Burn remaining shares and return collateral. * @param shares Pool shares. It will be in 18 decimals. */ function withdraw(uint256 shares) external virtual nonReentrant whenNotShutdown { _withdraw(shares); } /** * @notice Withdraw collateral based on given shares and the current share price. * Transfer earned rewards to caller. Burn shares and return collateral. * @dev No withdraw fee will be assessed when this function is called. * Only some white listed address can call this function. * @param shares Pool shares. It will be in 18 decimals. */ function withdrawByStrategy(uint256 shares) external virtual nonReentrant whenNotShutdown { require(feeWhiteList.get(_msgSender()) != 0, "Not a white listed address"); _withdrawByStrategy(shares); } /** * @notice Transfer tokens to multiple recipient * @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. * @param bits array of uint * @return true/false */ function multiTransfer(uint256[] memory bits) external returns (bool) { for (uint256 i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint256 amount = bits[i] & ((1 << 96) - 1); require(transfer(a, amount), "Transfer failed"); } return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @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 permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "Expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ) ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0) && signatory == owner, "Invalid signature"); _approve(owner, spender, amount); } /** * @notice Get price per share * @dev Return value will be in token defined decimals. */ function getPricePerShare() external view returns (uint256) { if (totalSupply() == 0) { return convertFrom18(1e18); } return totalValue().mul(1e18).div(totalSupply()); } /// @dev Convert to 18 decimals from token defined decimals. Default no conversion. function convertTo18(uint256 amount) public pure virtual returns (uint256) { return amount; } /// @dev Convert from 18 decimals to token defined decimals. Default no conversion. function convertFrom18(uint256 amount) public pure virtual returns (uint256) { return amount; } /// @dev Get fee collector address function feeCollector() public view virtual returns (address) { return controller.feeCollector(address(this)); } /// @dev Returns the token stored in the pool. It will be in token defined decimals. function tokensHere() public view virtual returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Returns sum of token locked in other contracts and token stored in the pool. * Default tokensHere. It will be in token defined decimals. */ function totalValue() public view virtual returns (uint256) { return tokensHere(); } /** * @notice Get withdraw fee for this pool * @dev Format: 1e16 = 1% fee */ function withdrawFee() public view virtual returns (uint256) { return controller.withdrawFee(address(this)); } /** * @dev Hook that is called just before burning tokens. To be used i.e. if * collateral is stored in a different contract and needs to be withdrawn. * @param share Pool share in 18 decimals */ function _beforeBurning(uint256 share) internal virtual {} /** * @dev Hook that is called just after burning tokens. To be used i.e. if * collateral stored in a different/this contract needs to be transferred. * @param amount Collateral amount in collateral token defined decimals. */ function _afterBurning(uint256 amount) internal virtual {} /** * @dev Hook that is called just before minting new tokens. To be used i.e. * if the deposited amount is to be transferred from user to this contract. * @param amount Collateral amount in collateral token defined decimals. */ function _beforeMinting(uint256 amount) internal virtual {} /** * @dev Hook that is called just after minting new tokens. To be used i.e. * if the deposited amount is to be transferred to a different contract. * @param amount Collateral amount in collateral token defined decimals. */ function _afterMinting(uint256 amount) internal virtual {} /** * @dev Calculate shares to mint based on the current share price and given amount. * @param amount Collateral amount in collateral token defined decimals. */ function _calculateShares(uint256 amount) internal view returns (uint256) { require(amount != 0, "amount is 0"); uint256 _totalSupply = totalSupply(); uint256 _totalValue = convertTo18(totalValue()); uint256 shares = (_totalSupply == 0 || _totalValue == 0) ? amount : amount.mul(_totalSupply).div(_totalValue); return shares; } /// @dev Deposit incoming token and mint pool token i.e. shares. function _deposit(uint256 amount) internal whenNotPaused { uint256 shares = _calculateShares(convertTo18(amount)); _beforeMinting(amount); _mint(_msgSender(), shares); _afterMinting(amount); emit Deposit(_msgSender(), shares, amount); } /// @dev Handle withdraw fee calculation and fee transfer to fee collector. function _handleFee(uint256 shares) internal returns (uint256 _sharesAfterFee) { if (withdrawFee() != 0) { uint256 _fee = shares.mul(withdrawFee()).div(1e18); _sharesAfterFee = shares.sub(_fee); _transfer(_msgSender(), feeCollector(), _fee); } else { _sharesAfterFee = shares; } } /// @dev Update pool reward of sender and receiver before transfer. function _beforeTokenTransfer( address from, address to, uint256 /* amount */ ) internal virtual override { address poolRewards = controller.poolRewards(address(this)); if (poolRewards != address(0)) { if (from != address(0)) { IPoolRewards(poolRewards).updateReward(from); } if (to != address(0)) { IPoolRewards(poolRewards).updateReward(to); } } } /// @dev Burns shares and returns the collateral value, after fee, of those. function _withdraw(uint256 shares) internal whenNotShutdown { require(shares != 0, "share is 0"); _beforeBurning(shares); uint256 sharesAfterFee = _handleFee(shares); uint256 amount = convertFrom18(sharesAfterFee.mul(convertTo18(totalValue())).div(totalSupply())); _burn(_msgSender(), sharesAfterFee); _afterBurning(amount); emit Withdraw(_msgSender(), shares, amount); } /// @dev Burns shares and returns the collateral value of those. function _withdrawByStrategy(uint256 shares) internal { require(shares != 0, "Withdraw must be greater than 0"); _beforeBurning(shares); uint256 amount = convertFrom18(shares.mul(convertTo18(totalValue())).div(totalSupply())); _burn(_msgSender(), shares); _afterBurning(amount); emit Withdraw(_msgSender(), shares, amount); } } // File: contracts/interfaces/uniswap/IUniswapV2Router01.sol pragma solidity 0.6.12; interface IUniswapV2Router01 { function factory() external pure returns (address); 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); } // File: contracts/interfaces/uniswap/IUniswapV2Router02.sol pragma solidity 0.6.12; interface IUniswapV2Router02 is IUniswapV2Router01 { 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; } // File: contracts/interfaces/vesper/IStrategy.sol pragma solidity 0.6.12; interface IStrategy { function rebalance() external; function deposit(uint256 amount) external; function beforeWithdraw() external; function withdraw(uint256 amount) external; function withdrawAll() external; function isUpgradable() external view returns (bool); function isReservedToken(address _token) external view returns (bool); function token() external view returns (address); function pool() external view returns (address); function totalLocked() external view returns (uint256); //Lifecycle functions function pause() external; function unpause() external; } // File: contracts/pools/VTokenBase.sol pragma solidity 0.6.12; abstract contract VTokenBase is PoolShareToken { address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; constructor( string memory name, string memory symbol, address _token, address _controller ) public PoolShareToken(name, symbol, _token, _controller) { require(_controller != address(0), "Controller address is zero"); } modifier onlyController() { require(address(controller) == _msgSender(), "Caller is not the controller"); _; } function pause() external onlyController { _pause(); } function unpause() external onlyController { _unpause(); } function shutdown() external onlyController { _shutdown(); } function open() external onlyController { _open(); } /// @dev Approve strategy to spend collateral token and strategy token of pool. function approveToken() external virtual onlyController { address strategy = controller.strategy(address(this)); token.safeApprove(strategy, MAX_UINT_VALUE); IERC20(IStrategy(strategy).token()).safeApprove(strategy, MAX_UINT_VALUE); } /// @dev Reset token approval of strategy. Called when updating strategy. function resetApproval() external virtual onlyController { address strategy = controller.strategy(address(this)); token.safeApprove(strategy, 0); IERC20(IStrategy(strategy).token()).safeApprove(strategy, 0); } /** * @dev Rebalance invested collateral to mitigate liquidation risk, if any. * Behavior of rebalance is driven by risk parameters defined in strategy. */ function rebalance() external virtual { IStrategy strategy = IStrategy(controller.strategy(address(this))); strategy.rebalance(); } /** * @dev Convert given ERC20 token into collateral token via Uniswap * @param _erc20 Token address */ function sweepErc20(address _erc20) external virtual { _sweepErc20(_erc20); } /// @dev Returns collateral token locked in strategy function tokenLocked() public view virtual returns (uint256) { IStrategy strategy = IStrategy(controller.strategy(address(this))); return strategy.totalLocked(); } /// @dev Returns total value of vesper pool, in terms of collateral token function totalValue() public view override returns (uint256) { return tokenLocked().add(tokensHere()); } /** * @dev After burning hook, it will be called during withdrawal process. * It will withdraw collateral from strategy and transfer it to user. */ function _afterBurning(uint256 _amount) internal override { uint256 balanceHere = tokensHere(); if (balanceHere < _amount) { _withdrawCollateral(_amount.sub(balanceHere)); balanceHere = tokensHere(); _amount = balanceHere < _amount ? balanceHere : _amount; } token.safeTransfer(_msgSender(), _amount); } /** * @dev Before burning hook. * Some actions, like resurface(), can impact share price and has to be called before withdraw. */ function _beforeBurning( uint256 /* shares */ ) internal override { IStrategy strategy = IStrategy(controller.strategy(address(this))); strategy.beforeWithdraw(); } function _beforeMinting(uint256 amount) internal override { token.safeTransferFrom(_msgSender(), address(this), amount); } function _withdrawCollateral(uint256 amount) internal virtual { IStrategy strategy = IStrategy(controller.strategy(address(this))); strategy.withdraw(amount); } function _sweepErc20(address _from) internal { IStrategy strategy = IStrategy(controller.strategy(address(this))); require( _from != address(token) && _from != address(this) && !strategy.isReservedToken(_from), "Not allowed to sweep" ); IUniswapV2Router02 uniswapRouter = IUniswapV2Router02(controller.uniswapRouter()); uint256 amt = IERC20(_from).balanceOf(address(this)); IERC20(_from).safeApprove(address(uniswapRouter), 0); IERC20(_from).safeApprove(address(uniswapRouter), amt); address[] memory path; if (address(token) == WETH) { path = new address[](2); path[0] = _from; path[1] = address(token); } else { path = new address[](3); path[0] = _from; path[1] = WETH; path[2] = address(token); } uniswapRouter.swapExactTokensForTokens(amt, 1, path, address(this), now + 30); } } // File: contracts/pools/VUSDC.sol pragma solidity 0.6.12; //solhint-disable no-empty-blocks contract VUSDC is VTokenBase { constructor(address _controller) public VTokenBase("vUSDC Pool", "vUSDC", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, _controller) {} /// @dev Convert to 18 decimals from token defined decimals. function convertTo18(uint256 _value) public pure override returns (uint256) { return _value.mul(10**12); } /// @dev Convert from 18 decimals to token defined decimals. function convertFrom18(uint256 _value) public pure override returns (uint256) { return _value.div(10**12); } }
Returns sum of token locked in other contracts and token stored in the pool. Default tokensHere. It will be in token defined decimals./
function totalValue() public view virtual returns (uint256) { return tokensHere(); }
324,878
// SPDX-License-Identifier: MIT // https://github.com/Brickken/license/blob/main/README.md pragma solidity ^0.8.0; import "@openzeppelin/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/openzeppelin-contracts/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/openzeppelin-contracts/contracts/utils/cryptography/MerkleProof.sol"; /** * @dev Extension of the underlying contract to support wrapping. * * Anyone can deposit underlying and receive a matching number of "wrapped" tokens. * At construction time, underlying tokens are transferred in and wrapped tokens are minted to the contract (so that advisor wallet can exchange them) * It has a `releaseTime` set in the constructor which is used to let the advisor wallet to burn their wrapped tokens in exchange * for underlying tokens only if `block.timestamp` is greater or equal than the `releaseTime`. * */ contract WBrickken is ERC20, AccessControlEnumerable { IERC20 public immutable underlying; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); uint256 private releaseTime_; constructor( IERC20 _underlyingToken, uint256 _releaseTime, uint256 _advisorsQuantity, address _advisorAddress ) ERC20("Wrapped Brickken", "WBKN") { require(address(_underlyingToken) != address(0x0), "Underlying token address is zero address"); require(_releaseTime >= block.timestamp, "Can't set a date in the past"); underlying = _underlyingToken; releaseTime_ = _releaseTime; // Assign mintable roles to the msg.sender _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); // Mint the same quantity of underlying that will be sent manually to this contract after construction _mint(_advisorAddress, _advisorsQuantity); } /** * @dev Allow a user to deposit underlying tokens and mint the corresponding number of wrapped tokens. * This function will be called to allocate the wrapped tokens to the parties involved. * After `releaseTime`, wrapped token holders can exchange them for underlying tokens deposited in this contract by using `release()`. */ function depositFor(address account, uint256 amount) public virtual onlyRole(MINTER_ROLE) returns (bool) { SafeERC20.safeTransferFrom(underlying, _msgSender(), address(this), amount); _mint(account, amount); return true; } /** * @dev Batch `depositFor` function */ function depositForBatched(address[] calldata accounts, uint256[] calldata amounts) public virtual onlyRole(MINTER_ROLE) returns (bool succeeded) { require(accounts.length == amounts.length, "Mismatch between accounts and amounts lenghts"); require(accounts.length > 0, "Invalid input lenghts"); for(uint256 i = 0; i<accounts.length; i++) { bool result = depositFor(accounts[i], amounts[i]); require(result, "Deposit failed for one of the provided accounts"); } succeeded = true; } /** * @return the time when the tokens can be released. */ function releaseTime() public view virtual returns (uint256) { return releaseTime_; } /** * @notice Transfers tokens held by the contract to beneficiary after `releaseTime` has passed. * It also burns wrapped tokens before sending the BKNs. * This function will be called by any wrapped token holder. */ function release(address account, uint256 amount) public virtual returns (bool) { require(block.timestamp >= releaseTime(), "Current time is before release time"); require(amount > 0, "No tokens to release"); _burn(_msgSender(), amount); SafeERC20.safeTransfer(underlying, account, amount); return true; } /** * @dev Mint wrapped token to cover any BKN that would have been transfered by mistake. * @notice Only the minter can call this function */ function recover(address to) public virtual onlyRole(MINTER_ROLE) { _recover(to); } /** * @dev Calculate the difference between the contract's balance in underlying * and the total supply of wrapped tokens. If there's any difference which is greater than zero * then mint that as wrapped tokens and send it to `account` */ function _recover(address account) internal virtual returns (uint256) { uint256 value = underlying.balanceOf(address(this)) - totalSupply(); _mint(account, value); return value; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 pragma solidity ^0.8.0; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // 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; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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 Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{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 granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Batch `depositFor` function/
function depositForBatched(address[] calldata accounts, uint256[] calldata amounts) public virtual onlyRole(MINTER_ROLE) returns (bool succeeded) { require(accounts.length == amounts.length, "Mismatch between accounts and amounts lenghts"); require(accounts.length > 0, "Invalid input lenghts"); for(uint256 i = 0; i<accounts.length; i++) { bool result = depositFor(accounts[i], amounts[i]); require(result, "Deposit failed for one of the provided accounts"); } succeeded = true; }
1,401,519
pragma solidity 0.4.25; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract EmcoTokenInterface is ERC20 { function setReferral(bytes32 _code) public; function setReferralCode(bytes32 _code) public view returns (bytes32); function referralCodeOwners(bytes32 _code) public view returns (address); function referrals(address _address) public view returns (address); function userReferralCodes(address _address) public view returns (bytes32); } /** * @title EMCO Clan * @dev EMCO Clan */ contract Clan is Ownable { using SafeMath for uint256; mapping(address => uint256) public rewards; mapping(uint256 => uint256) public epochRewards; mapping(address => uint256) public epochJoined; mapping(uint => uint256) private membersNumForEpoch; mapping(address => mapping(uint => bool)) public reclaimedRewards; uint public lastMembersNumber = 0; event UserJoined(address userAddress); event UserLeaved(address userAddress); uint public startBlock; uint public epochLength; uint public ownersReward; EmcoToken emco; address public clanOwner; constructor(address _clanOwner, address _emcoToken, uint256 _epochLength) public { clanOwner = _clanOwner; startBlock = block.number; epochLength = _epochLength; emco = EmcoToken(_emcoToken); } function replenish(uint amount) public onlyOwner { //update members number for epoch if it was not set //we should ensure that for each epoch that has a reward members num is set uint currentEpoch = getCurrentEpoch(); if(membersNumForEpoch[currentEpoch] == 0) { membersNumForEpoch[currentEpoch] = lastMembersNumber; } uint ownersPart; if(membersNumForEpoch[currentEpoch] == 0) { //first user joined, mines on current epoch, but user is able to redeem for next epoch ownersPart = amount; } else { ownersPart = amount.div(10); epochRewards[currentEpoch] = epochRewards[currentEpoch].add(amount - ownersPart); } ownersReward = ownersReward.add(ownersPart); } function getMembersForEpoch(uint epochNumber) public view returns (uint membersNumber) { return membersNumForEpoch[epochNumber]; } function getCurrentEpoch() public view returns (uint256) { return (block.number - startBlock) / epochLength; } //only token can join a user to a clan. Owner is an EMCO Token contract function join(address user) public onlyOwner { emit UserJoined(user); uint currentEpoch = getCurrentEpoch(); epochJoined[user] = currentEpoch + 1; //increment members number uint currentMembersNum = lastMembersNumber; if(currentMembersNum == 0) { membersNumForEpoch[currentEpoch + 1] = currentMembersNum + 1; } else { membersNumForEpoch[currentEpoch + 1] = membersNumForEpoch[currentEpoch + 1] + 1; } //update last members num lastMembersNumber = membersNumForEpoch[currentEpoch + 1]; } function leaveClan(address user) public onlyOwner { epochJoined[user] = 0; emit UserLeaved(user); //decrement members number uint currentEpoch = getCurrentEpoch(); uint currentMembersNum = lastMembersNumber; if(currentMembersNum != 0) { membersNumForEpoch[currentEpoch + 1] = membersNumForEpoch[currentEpoch + 1] - 1; } //update last members num lastMembersNumber = membersNumForEpoch[currentEpoch + 1]; } function calculateReward(uint256 epoch) public view returns (uint256) { return epochRewards[epoch].div(membersNumForEpoch[epoch]); } function reclaimOwnersReward() public { require(msg.sender == clanOwner); emco.transfer(msg.sender, ownersReward); ownersReward = 0; } //get your bonus for specific epoch function reclaimReward(uint256 epoch) public { uint currentEpoch = getCurrentEpoch(); require(currentEpoch > epoch); require(epochJoined[msg.sender] != 0); require(epochJoined[msg.sender] <= epoch); require(reclaimedRewards[msg.sender][epoch] == false); uint userReward = calculateReward(epoch); require(userReward > 0); require(emco.transfer(msg.sender, userReward)); reclaimedRewards[msg.sender][epoch] = true; } } /** * @title Emco token 2nd version * @dev Emco token implementation */ contract EmcoToken is StandardToken, Ownable { string public constant name = "EmcoToken"; string public constant symbol = "EMCO"; uint8 public constant decimals = 18; // uint public constant INITIAL_SUPPLY = 1500000 * (10 ** uint(decimals)); uint public constant MAX_SUPPLY = 36000000 * (10 ** uint(decimals)); mapping (address => uint) public miningBalances; mapping (address => uint) public lastMiningBalanceUpdateTime; //clans mapping (address => address) public joinedClans; mapping (address => address) public userClans; mapping (address => bool) public clanRegistry; mapping (address => uint256) public inviteeCount; address systemAddress; EmcoTokenInterface private oldContract; uint public constant DAY_MINING_DEPOSIT_LIMIT = 360000 * (10 ** uint(decimals)); uint public constant TOTAL_MINING_DEPOSIT_LIMIT = 3600000 * (10 ** uint(decimals)); uint currentDay; uint currentDayDeposited; uint public miningTotalDeposited; mapping(address => bytes32) private userRefCodes; mapping(bytes32 => address) private refCodeOwners; mapping(address => address) private refs; event Mine(address indexed beneficiary, uint value); event MiningBalanceUpdated(address indexed owner, uint amount, bool isDeposit); event Migrate(address indexed user, uint256 amount); event TransferComment(address indexed to, uint256 amount, bytes comment); event SetReferral(address whoSet, address indexed referrer); constructor(address emcoAddress) public { systemAddress = msg.sender; oldContract = EmcoTokenInterface(emcoAddress); } function migrate(uint _amount) public { require(oldContract.transferFrom(msg.sender, this, _amount)); totalSupply_ = totalSupply_.add(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); emit Migrate(msg.sender, _amount); emit Transfer(address(0), msg.sender, _amount); } function setReferralCode(bytes32 _code) public returns (bytes32) { require(_code != ""); require(refCodeOwners[_code] == address(0)); require(oldContract.referralCodeOwners(_code) == address(0)); require(userReferralCodes(msg.sender) == ""); userRefCodes[msg.sender] = _code; refCodeOwners[_code] = msg.sender; return _code; } function referralCodeOwners(bytes32 _code) public view returns (address owner) { address refCodeOwner = refCodeOwners[_code]; if(refCodeOwner == address(0)) { return oldContract.referralCodeOwners(_code); } else { return refCodeOwner; } } function userReferralCodes(address _address) public view returns (bytes32) { bytes32 code = oldContract.userReferralCodes(_address); if(code != "") { return code; } else { return userRefCodes[_address]; } } function referrals(address _address) public view returns (address) { address refInOldContract = oldContract.referrals(_address); if(refInOldContract != address(0)) { return refInOldContract; } else { return refs[_address]; } } function setReferral(bytes32 _code) public { require(refCodeOwners[_code] != address(0)); require(referrals(msg.sender) == address(0)); require(oldContract.referrals(msg.sender) == address(0)); address referrer = refCodeOwners[_code]; require(referrer != msg.sender, "Can not invite yourself"); refs[msg.sender] = referrer; inviteeCount[referrer] = inviteeCount[referrer].add(1); emit SetReferral(msg.sender, referrer); } function transferWithComment(address _to, uint256 _value, bytes _comment) public returns (bool) { emit TransferComment(_to, _value, _comment); return transfer(_to, _value); } /** * Create a clan */ function createClan(uint256 epochLength) public returns (address clanAddress) { require(epochLength >= 175200); //min epoch length about a month //check if there is a clan already. If so, throw require(userClans[msg.sender] == address(0x0)); //check if user has at least 10 invitees require(inviteeCount[msg.sender] >= 10); //instantiate new instance of contract Clan clan = new Clan(msg.sender, this, epochLength); //register clan to mapping userClans[msg.sender] = clan; clanRegistry[clan] = true; return clan; } function joinClan(address clanAddress) public { //ensure than such clan exists require(clanRegistry[clanAddress]); require(joinedClans[msg.sender] == address(0x0)); //join user to clan Clan clan = Clan(clanAddress); clan.join(msg.sender); //set clan to user joinedClans[msg.sender] = clanAddress; } function leaveClan() public { address clanAddress = joinedClans[msg.sender]; require(clanAddress != address(0x0)); Clan clan = Clan(clanAddress); clan.leaveClan(msg.sender); //unregister user from clan joinedClans[msg.sender] = address(0x0); } /** * Update invitees count */ function updateInviteesCount(address invitee, uint256 count) public onlyOwner { inviteeCount[invitee] = count; } /** * @dev Gets the balance of specified address (amount of tokens on main balance * plus amount of tokens on mining balance). * @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 (uint balance) { return balances[_owner].add(miningBalances[_owner]); } /** * @dev Gets the mining balance if caller. * @param _owner The address to query the balance of. * @return An uint256 representing the amount of tokens of caller's mining balance */ function miningBalanceOf(address _owner) public view returns (uint balance) { return miningBalances[_owner]; } /** * @dev Moves specified amount of tokens from main balance to mining balance * @param _amount An uint256 representing the amount of tokens to transfer to main balance */ function depositToMiningBalance(uint _amount) public { require(balances[msg.sender] >= _amount, "not enough tokens"); require(getCurrentDayDeposited().add(_amount) <= DAY_MINING_DEPOSIT_LIMIT, "Day mining deposit exceeded"); require(miningTotalDeposited.add(_amount) <= TOTAL_MINING_DEPOSIT_LIMIT, "Total mining deposit exceeded"); balances[msg.sender] = balances[msg.sender].sub(_amount); miningBalances[msg.sender] = miningBalances[msg.sender].add(_amount); miningTotalDeposited = miningTotalDeposited.add(_amount); updateCurrentDayDeposited(_amount); lastMiningBalanceUpdateTime[msg.sender] = now; emit MiningBalanceUpdated(msg.sender, _amount, true); } /** * @dev Moves specified amount of tokens from mining balance to main balance * @param _amount An uint256 representing the amount of tokens to transfer to mining balance */ function withdrawFromMiningBalance(uint _amount) public { require(miningBalances[msg.sender] >= _amount, "not enough mining tokens"); miningBalances[msg.sender] = miningBalances[msg.sender].sub(_amount); balances[msg.sender] = balances[msg.sender].add(_amount); //updating mining limits miningTotalDeposited = miningTotalDeposited.sub(_amount); lastMiningBalanceUpdateTime[msg.sender] = now; emit MiningBalanceUpdated(msg.sender, _amount, false); } /** * @dev Mine tokens. For every 24h for each user�s token on mining balance, * 1% is burnt on mining balance and Reward % is minted to the main balance. 15% fee of difference * between minted coins and burnt coins goes to system address. */ function mine() public { require(totalSupply_ < MAX_SUPPLY, "mining is over"); uint reward = getReward(totalSupply_); uint daysForReward = getDaysForReward(); uint mintedAmount = miningBalances[msg.sender].mul(reward.sub(1000000000)) .mul(daysForReward).div(100000000000); require(mintedAmount != 0); uint amountToBurn = miningBalances[msg.sender].mul(daysForReward).div(100); //check exceeding max number of tokens if(totalSupply_.add(mintedAmount) > MAX_SUPPLY) { uint availableToMint = MAX_SUPPLY.sub(totalSupply_); amountToBurn = availableToMint.div(mintedAmount).mul(amountToBurn); mintedAmount = availableToMint; } totalSupply_ = totalSupply_.add(mintedAmount); miningBalances[msg.sender] = miningBalances[msg.sender].sub(amountToBurn); balances[msg.sender] = balances[msg.sender].add(amountToBurn); uint userReward; uint referrerReward = 0; address referrer = referrals(msg.sender); if(referrer == address(0)) { userReward = mintedAmount.mul(85).div(100); } else { userReward = mintedAmount.mul(86).div(100); referrerReward = mintedAmount.div(100); balances[referrer] = balances[referrer].add(referrerReward); emit Mine(referrer, referrerReward); emit Transfer(address(0), referrer, referrerReward); } balances[msg.sender] = balances[msg.sender].add(userReward); emit Mine(msg.sender, userReward); emit Transfer(address(0), msg.sender, userReward); //update limits miningTotalDeposited = miningTotalDeposited.sub(amountToBurn); emit MiningBalanceUpdated(msg.sender, amountToBurn, false); //set system fee uint systemFee = mintedAmount.sub(userReward).sub(referrerReward); balances[systemAddress] = balances[systemAddress].add(systemFee); emit Mine(systemAddress, systemFee); emit Transfer(address(0), systemAddress, systemFee); lastMiningBalanceUpdateTime[msg.sender] = now; //assign to clan address mintClanReward(mintedAmount.mul(5).div(1000)); } function mintClanReward(uint reward) private { //check if user has a clan address clanAddress = joinedClans[msg.sender]; if(clanAddress != address(0x0)) { // check if this clan is registered require(clanRegistry[clanAddress], "clan is not registered"); // send appropriate amount of EMCO to clan address balances[clanAddress] = balances[clanAddress].add(reward); Clan clan = Clan(clanAddress); clan.replenish(reward); totalSupply_ = totalSupply_.add(reward); } } /** * @dev Set system address * @param _systemAddress An address to set */ function setSystemAddress(address _systemAddress) public onlyOwner { systemAddress = _systemAddress; } /** * @dev Get sum of deposits to mining accounts for current day */ function getCurrentDayDeposited() public view returns (uint) { if(now / 1 days == currentDay) { return currentDayDeposited; } else { return 0; } } /** * @dev Get number of days for reward on mining. Maximum 100 days. * @return An uint256 representing number of days user will get reward for. */ function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; } else { uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; } else { return value; } } } /** * @dev Calculate current mining reward based on total supply of tokens * @return An uint256 representing reward in percents multiplied by 1000000000 */ function getReward(uint _totalSupply) public pure returns (uint rewardPercent){ uint rewardFactor = 1000000 * (10 ** uint256(decimals)); uint decreaseFactor = 41666666; if(_totalSupply < 23 * rewardFactor) { return 2000000000 - (decreaseFactor.mul(_totalSupply.div(rewardFactor))); } if(_totalSupply < MAX_SUPPLY) { return 1041666666; } else { return 1000000000; } } function updateCurrentDayDeposited(uint _addedTokens) private { if(now / 1 days == currentDay) { currentDayDeposited = currentDayDeposited.add(_addedTokens); } else { currentDay = now / 1 days; currentDayDeposited = _addedTokens; } } }
Get number of days for reward on mining. Maximum 100 days. return An uint256 representing number of days user will get reward for./
function getDaysForReward() public view returns (uint rewardDaysNum){ if(lastMiningBalanceUpdateTime[msg.sender] == 0) { return 0; uint value = (now - lastMiningBalanceUpdateTime[msg.sender]) / (1 days); if(value > 100) { return 100; return value; } } }
12,540,327
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; // BottlenoseToken with Governance. contract NarwhalToken is ERC20, Ownable, ERC20Burnable { using SafeMath for uint256; // Burn address address public constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD; uint256 private _cap; // Max transfer amount rate in basis points. (default is 1% of total supply) uint16 public maxTransferAmountRate = 100; // Min value of the max transfer amount rate. (0.5%) uint16 public constant maxTransferMinRate = 50; // Addresses that excluded from antiWhale mapping(address => bool) private _excludedFromAntiWhale; // Is the transfer enabled? (False by default) bool public isTransactionEnabled = false; // Blacklisted addresses mapping(address => bool) private blackList; // anti-bot end block uint256 public antiBotBlock; // The duration that the anti-bot function last: 200 blocks ~ 10mins (from launch) uint256 public constant ANTI_BOT_TIME = 200; // Events event OperatorTransferred(address indexed previousOperator, address indexed newOperator); event MaxTransferAmountRateUpdated(address indexed operator, uint256 previousRate, uint256 newRate); modifier antiWhale(address sender, address recipient, uint256 amount) { if (maxTransferAmount() > 0) { if (_excludedFromAntiWhale[sender] == false && _excludedFromAntiWhale[recipient] == false) { require(amount <= maxTransferAmount(), "TOKEN::antiWhale: Transfer amount exceeds the maxTransferAmount"); } } _; } /** * @dev Blocks transaction before launch, so can inject liquidity before launch */ modifier blockTransaction(address sender) { if (isTransactionEnabled == false) { require(sender == owner(), "TOKEN::blockTransaction: Transfers can only be done by operator."); } _; } modifier antiBot(address recipient) { if (isTransactionEnabled && block.number <= antiBotBlock) { require(balanceOf(recipient) <= maxTransferAmount(), "TOKEN:: antiBot: Suspected bot activity"); } _; } /** * @notice Constructs the BottlenoseToken contract. */ constructor(uint256 nCap) public ERC20("Narwhal Token", "NAR") { require(nCap > 0, "GovernanceToken: cap is 0"); _cap = nCap; _excludedFromAntiWhale[msg.sender] = true; _excludedFromAntiWhale[address(0)] = true; _excludedFromAntiWhale[address(this)] = true; _excludedFromAntiWhale[BURN_ADDRESS] = true; // Setup LP pools wtih 10,000 tokens @ $2k for 0.2 _mint(msg.sender, 10000000000000000000000); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { require(ERC20.totalSupply() + _amount <= cap(), "GovernanceToken: cap exceeded"); _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /// @dev overrides transfer function to meet tokenomics of BTN function _transfer(address sender, address recipient, uint256 amount) internal virtual override blockTransaction(sender) antiWhale(sender, recipient, amount) antiBot(recipient) { require(blackList[sender] == false,"TOKEN::transfer: You're blacklisted"); super._transfer(sender, recipient, amount); } /** * @dev Returns the max transfer amount. */ function maxTransferAmount() public view returns (uint256) { return totalSupply().mul(maxTransferAmountRate).div(10000); } /** * @dev Returns the address is excluded from antiWhale or not. */ function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; } /** * @dev Update the max transfer amount rate. * Can only be called by the current operator. */ function updateMaxTransferAmountRate(uint16 _maxTransferAmountRate) public onlyOwner { require(_maxTransferAmountRate <= 10000, "TOKEN::updateMaxTransferAmountRate: Max transfer amount rate must not exceed the maximum rate."); require(_maxTransferAmountRate >= maxTransferMinRate,"TOKEN::updateMaxTransferAmountRate: Max transfer amount rate must be grater than min rate"); emit MaxTransferAmountRateUpdated(msg.sender, maxTransferAmountRate, _maxTransferAmountRate); maxTransferAmountRate = _maxTransferAmountRate; } /** * @dev Exclude or include an address from antiWhale. * Can only be called by the current operator. */ function setExcludedFromAntiWhale(address _account, bool _excluded) public onlyOwner { _excludedFromAntiWhale[_account] = _excluded; } /** * @dev Enable transactions. * Can only be called once by the current operator. */ function enableTransaction() public onlyOwner { require(isTransactionEnabled == false,"TOKEN::enableTransaction: This meothod can only be called once"); isTransactionEnabled = true; antiBotBlock = block.number.add(ANTI_BOT_TIME); } /** * @dev Exclude or include an address from blackList. */ function addToBlackList(address _account, bool _excluded) public onlyOwner { blackList[_account] = _excluded; } /** * @dev Returns the address is excluded from blackList or not. */ function isBlackListed(address _account) public view returns (bool) { return blackList[_account]; } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TOKEN::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "TOKEN::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "TOKEN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require(blockNumber < block.number, "TOKEN::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BTNs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TOKEN::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
Returns the address is excluded from antiWhale or not./
function isExcludedFromAntiWhale(address _account) public view returns (bool) { return _excludedFromAntiWhale[_account]; }
12,787,094
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.9.0; import './common/SafeMath.sol'; import './common/Destructible.sol'; /** @title Credit contract. * Inherits the Ownable and Destructible contracts. */ contract Credit is Destructible { /** @dev Usings */ // Using SafeMath for our calculations with uints. using SafeMath for uint; /** @dev State variables */ // Borrower is the person who generated the credit contract. address borrower; // Amount requested to be funded (in wei). uint requestedAmount; // Amount that will be returned by the borrower (including the interest). uint returnAmount; // Currently repaid amount. uint repaidAmount; // Credit interest. uint interest; // Requested number of repayment installments. uint requestedRepayments; // Remaining repayment installments. uint remainingRepayments; // The value of the repayment installment. uint repaymentInstallment; // The timestamp of credit creation. uint requestedDate; // The timestamp of last repayment date. uint lastRepaymentDate; // Description of the credit. bytes32 description; // Active state of the credit. bool active = true; /** Stages that every credit contract gets trough. * investment - During this state only investments are allowed. * repayment - During this stage only repayments are allowed. * interestReturns - This stage gives investors opportunity to request their returns. * expired - This is the stage when the contract is finished its purpose. * fraud - The borrower was marked as fraud. */ enum State { investment, repayment, interestReturns, expired, revoked, fraud } State state; // Storing the lenders for this credit. mapping(address => bool) public lenders; // Storing the invested amount by each lender. mapping(address => uint) lendersInvestedAmount; // Store the lenders count, later needed for revoke vote. uint lendersCount = 0; // Revoke votes count. uint revokeVotes = 0; // Revoke voters. mapping(address => bool) revokeVoters; // Time needed for a revoke voting to start. // To be changed in production accordingly. uint revokeTimeNeeded = block.timestamp + 1 seconds; // Revoke votes count. uint fraudVotes = 0; // Revoke voters. mapping(address => bool) fraudVoters; /** @dev Events * */ event LogCreditInitialized(address indexed _address, uint indexed timestamp); event LogCreditStateChanged(State indexed state, uint indexed timestamp); event LogCreditStateActiveChanged(bool indexed active, uint indexed timestamp); event LogBorrowerWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentInstallment(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentFinished(address indexed _address, uint indexed timestamp); event LogBorrowerChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerIsFraud(address indexed _address, bool indexed fraudStatus, uint indexed timestamp); event LogLenderInvestment(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderVoteForRevoking(address indexed _address, uint indexed timestamp); event LogLenderVoteForFraud(address indexed _address, uint indexed timestamp); event LogLenderRefunded(address indexed _address, uint indexed _amount, uint indexed timestamp); /** @dev Modifiers * */ modifier isActive() { require(active == true); _; } modifier onlyBorrower() { require(msg.sender == borrower); _; } modifier onlyLender() { require(lenders[msg.sender] == true); _; } modifier canAskForInterest() { require(state == State.interestReturns); require(lendersInvestedAmount[msg.sender] > 0); _; } modifier canInvest() { require(state == State.investment); _; } modifier canRepay() { require(state == State.repayment); _; } modifier canWithdraw() { require(this.balance >= requestedAmount); _; } modifier isNotFraud() { require(state != State.fraud); _; } modifier isRevokable() { require(block.timestamp >= revokeTimeNeeded); require(state == State.investment); _; } modifier isRevoked() { require(state == State.revoked); _; } /** @dev Constructor. * @param _requestedAmount Requested credit amount (in wei). * @param _requestedRepayments Requested number of repayments. * @param _description Credit description. */ constructor(uint _requestedAmount, uint _requestedRepayments, uint _interest, bytes32 _description) { /** Set the borrower of the contract to the tx.origin * We are using tx.origin, because the contract is going to be published * by the main contract and msg.sender will break our logic. */ borrower = tx.origin; // Set the interest for the credit. interest = _interest; // Set the requested amount. requestedAmount = _requestedAmount; // Set the requested repayments. requestedRepayments = _requestedRepayments; /** Set the remaining repayments. * Initially this is equal to the requested repayments. */ remainingRepayments = _requestedRepayments; /** Calculate the amount to be returned by the borrower. * At this point this is the addition of the requested amount and the interest. */ returnAmount = requestedAmount.add(interest); /** Calculating the repayment installment. * We divide the amount to be returned by the requested repayments count to get it. */ repaymentInstallment = returnAmount.div(requestedRepayments); // Set the credit description. description = _description; // Set the initialization date. requestedDate = block.timestamp; // Log credit initialization. LogCreditInitialized(borrower, block.timestamp); } /** @dev Get current balance. * @return this.balance. */ function getBalance() public view returns (uint256) { return this.balance; } /** @dev Invest function. * Provides functionality for person to invest in someone's credit, * incentivised by the return of interest. */ function invest() public canInvest payable { // Initialize an memory variable for the extra money that may have been sent. uint extraMoney = 0; // Check if contract balance is reached the requested amount. if (this.balance >= requestedAmount) { // Calculate the extra money that may have been sent. extraMoney = this.balance.sub(requestedAmount); // Assert the calculations assert(requestedAmount == this.balance.sub(extraMoney)); // Assert for possible underflow / overflow assert(extraMoney <= msg.value); // Check if extra money is greater than 0 wei. if (extraMoney > 0) { // Return the extra money to the sender. msg.sender.transfer(extraMoney); // Log change returned. LogLenderChangeReturned(msg.sender, extraMoney, block.timestamp); } // Set the contract state to repayment. state = State.repayment; // Log state change. LogCreditStateChanged(state, block.timestamp); } /** Add the investor to the lenders mapping. * So that we know he invested in this contract. */ lenders[msg.sender] = true; // Increment the lenders count. lendersCount++; // Add the amount invested to the amount mapping. lendersInvestedAmount[msg.sender] = lendersInvestedAmount[msg.sender].add(msg.value.sub(extraMoney)); // Log lender invested amount. LogLenderInvestment(msg.sender, msg.value.sub(extraMoney), block.timestamp); } /** @dev Repayment function. * Allows borrower to make repayment installments. */ function repay() public onlyBorrower canRepay payable { // The remaining repayments should be greater than 0 to continue. require(remainingRepayments > 0); // The value sent should be greater than the repayment installment. require(msg.value >= repaymentInstallment); /** Assert that the amount to be returned is greater * than the sum of repayments made until now. * Otherwise the credit is already repaid. */ assert(repaidAmount < returnAmount); // Decrement the remaining repayments. remainingRepayments--; // Update last repayment date. lastRepaymentDate = block.timestamp; // Initialize an memory variable for the extra money that may have been sent. uint extraMoney = 0; /** Check if the value (in wei) that is being sent is greather than the repayment installment. * In this case we should return the change to the msg.sender. */ if (msg.value > repaymentInstallment) { // Calculate the extra money being sent in the transaction. extraMoney = msg.value.sub(repaymentInstallment); // Assert the calculations. assert(repaymentInstallment == msg.value.sub(extraMoney)); // Assert for underflow. assert(extraMoney <= msg.value); // Return the change/extra money to the msg.sender. msg.sender.transfer(extraMoney); // Log the return of the extra money. LogBorrowerChangeReturned(msg.sender, extraMoney, block.timestamp); } // Log borrower installment received. LogBorrowerRepaymentInstallment(msg.sender, msg.value.sub(extraMoney), block.timestamp); // Add the repayment installment amount to the total repaid amount. repaidAmount = repaidAmount.add(msg.value.sub(extraMoney)); // Check the repaid amount reached the amount to be returned. if (repaidAmount == returnAmount) { // Log credit repaid. LogBorrowerRepaymentFinished(msg.sender, block.timestamp); // Set the credit state to "returning interests". state = State.interestReturns; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Withdraw function. * It can only be executed while contract is in active state. * It is only accessible to the borrower. * It is only accessible if the needed amount is gathered in the contract. * It can only be executed once. * Transfers the gathered amount to the borrower. */ function withdraw() public isActive onlyBorrower canWithdraw isNotFraud { // Set the state to repayment so we can avoid reentrancy. state = State.repayment; // Log state change. LogCreditStateChanged(state, block.timestamp); // Log borrower withdrawal. LogBorrowerWithdrawal(msg.sender, this.balance, block.timestamp); // Transfer the gathered amount to the credit borrower. borrower.transfer(this.balance); } /** @dev Request interest function. * It can only be executed while contract is in active state. * It is only accessible to lenders. * It is only accessible if lender funded 1 or more wei. * It can only be executed once. * Transfers the lended amount + interest to the lender. */ function requestInterest() public isActive onlyLender canAskForInterest { // Calculate the amount to be returned to lender. // uint lenderReturnAmount = lendersInvestedAmount[msg.sender].mul(returnAmount.div(lendersCount).div(lendersInvestedAmount[msg.sender])); uint lenderReturnAmount = returnAmount / lendersCount; // Assert the contract has enough balance to pay the lender. assert(this.balance >= lenderReturnAmount); // Transfer the return amount with interest to the lender. msg.sender.transfer(lenderReturnAmount); // Log the transfer to lender. LogLenderWithdrawal(msg.sender, lenderReturnAmount, block.timestamp); // Check if the contract balance is drawned. if (this.balance == 0) { // Set the active state to false. active = false; // Log active state change. LogCreditStateActiveChanged(active, block.timestamp); // Set the contract stage to expired e.g. its lifespan is over. state = State.expired; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Function to get the whole credit information. * @return borrower * @return description * @return requestedAmount * @return requestedRepayments * @return remainingRepayments * @return interest * @return returnAmount * @return state * @return active * @return this.balance */ function getCreditInfo() public view returns (address, bytes32, uint, uint, uint, uint, uint, uint, State, bool, uint) { return ( borrower, description, requestedAmount, requestedRepayments, repaymentInstallment, remainingRepayments, interest, returnAmount, state, active, this.balance ); } /** @dev Function for revoking the credit. */ function revokeVote() public isActive isRevokable onlyLender { // Require only one vote per lender. require(revokeVoters[msg.sender] == false); // Increment the revokeVotes. revokeVotes++; // Note the lender has voted. revokeVoters[msg.sender] == true; // Log lender vote for revoking the credit contract. LogLenderVoteForRevoking(msg.sender, block.timestamp); // If the consensus is reached. if (lendersCount == revokeVotes) { // Call internal revoke function. revoke(); } } /** @dev Revoke internal function. */ function revoke() internal { // Change the state to revoked. state = State.revoked; // Log credit revoked. LogCreditStateChanged(state, block.timestamp); } /** @dev Function for refunding people. */ function refund() public isActive onlyLender isRevoked { // assert the contract have enough balance. assert(this.balance >= lendersInvestedAmount[msg.sender]); // Transfer the return amount with interest to the lender. msg.sender.transfer(lendersInvestedAmount[msg.sender]); // Log the transfer to lender. LogLenderRefunded(msg.sender, lendersInvestedAmount[msg.sender], block.timestamp); // Check if the contract balance is drawned. if (this.balance == 0) { // Set the active state to false. active = false; // Log active status change. LogCreditStateActiveChanged(active, block.timestamp); // Set the contract stage to expired e.g. its lifespan is over. state = State.expired; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Function for voting the borrower as fraudster. */ function fraudVote() public isActive onlyLender returns (bool) { // A lender could vote only once. require(fraudVoters[msg.sender] == false); // Increment fraudVotes count. fraudVotes++; // Note the lender has voted. fraudVoters[msg.sender] == true; // Log lenders vote for fraud LogLenderVoteForFraud(msg.sender, block.timestamp); // Check if consensus is reached. if (lendersCount == fraudVotes) { // Invoke fraud function. return fraud(); } return true; } /** @dev Fraund function * @return * calls the owner contract and marks the borrower as fraudster. */ function fraud() internal returns (bool) { // call the owner address function with param borrower's address bool fraudStatusResult = owner.call(bytes4(keccak256("setFraudStatus(address)")), borrower); // Log user marked as fraud. LogBorrowerIsFraud(borrower, fraudStatusResult, block.timestamp); return fraudStatusResult; } /** @dev Change state function. * @param _state New state. * Only accessible to the owner of the contract. * Changes the state of the contract. */ function changeState(State _state) external onlyOwner returns (uint) { state = _state; // Log state change. LogCreditStateChanged(state, block.timestamp); } /** @dev Toggle active state function. * Only accessible to the owner of the contract. * Toggles the active state of the contract. * @return bool */ function toggleActive() external onlyOwner returns (bool) { active = !active; // Log active status change. LogCreditStateActiveChanged(active, block.timestamp); return active; } }
Toggle active state function. Only accessible to the owner of the contract. Toggles the active state of the contract. return bool/ Log active status change.
function toggleActive() external onlyOwner returns (bool) { active = !active; LogCreditStateActiveChanged(active, block.timestamp); return active; }
1,014,002
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; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @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(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract LittlePhilCoin is MintableToken, PausableToken { string public name = "Little Phil Coin"; string public symbol = "LPC"; uint8 public decimals = 18; constructor () public { // Pause token on creation and only unpause after ICO pause(); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } contract InitialSupplyCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; uint256 public constant decimals = 18; // Wallet properties address public companyWallet; address public teamWallet; address public projectWallet; address public advisorWallet; address public bountyWallet; address public airdropWallet; // Team locked tokens TokenTimelock public teamTimeLock1; TokenTimelock public teamTimeLock2; // Reserved tokens uint256 public constant companyTokens = SafeMath.mul(150000000, (10 ** decimals)); uint256 public constant teamTokens = SafeMath.mul(150000000, (10 ** decimals)); uint256 public constant projectTokens = SafeMath.mul(150000000, (10 ** decimals)); uint256 public constant advisorTokens = SafeMath.mul(100000000, (10 ** decimals)); uint256 public constant bountyTokens = SafeMath.mul(30000000, (10 ** decimals)); uint256 public constant airdropTokens = SafeMath.mul(20000000, (10 ** decimals)); bool private isInitialised = false; constructor( address[6] _wallets ) public { address _companyWallet = _wallets[0]; address _teamWallet = _wallets[1]; address _projectWallet = _wallets[2]; address _advisorWallet = _wallets[3]; address _bountyWallet = _wallets[4]; address _airdropWallet = _wallets[5]; require(_companyWallet != address(0)); require(_teamWallet != address(0)); require(_projectWallet != address(0)); require(_advisorWallet != address(0)); require(_bountyWallet != address(0)); require(_airdropWallet != address(0)); // Set reserved wallets companyWallet = _companyWallet; teamWallet = _teamWallet; projectWallet = _projectWallet; advisorWallet = _advisorWallet; bountyWallet = _bountyWallet; airdropWallet = _airdropWallet; // Lock team tokens in wallet over time periods teamTimeLock1 = new TokenTimelock(token, teamWallet, uint64(now + 182 days)); teamTimeLock2 = new TokenTimelock(token, teamWallet, uint64(now + 365 days)); } /** * Function: Distribute initial token supply */ function setupInitialSupply() internal onlyOwner { require(isInitialised == false); uint256 teamTokensSplit = teamTokens.mul(50).div(100); // Distribute tokens to reserved wallets LittlePhilCoin(token).mint(companyWallet, companyTokens); LittlePhilCoin(token).mint(projectWallet, projectTokens); LittlePhilCoin(token).mint(advisorWallet, advisorTokens); LittlePhilCoin(token).mint(bountyWallet, bountyTokens); LittlePhilCoin(token).mint(airdropWallet, airdropTokens); LittlePhilCoin(token).mint(address(teamTimeLock1), teamTokensSplit); LittlePhilCoin(token).mint(address(teamTimeLock2), teamTokensSplit); isInitialised = true; } } /** * @title WhitelistedCrowdsale * @dev Crowdsale in which only whitelisted users can contribute. */ contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title MintedCrowdsale * @dev Extension of Crowdsale contract whose tokens are minted in each purchase. * Token ownership should be transferred to MintedCrowdsale for minting. */ contract MintedCrowdsale is Crowdsale { /** * @dev Overrides delivery by minting tokens upon purchase. * @param _beneficiary Token purchaser * @param _tokenAmount Number of tokens to be minted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title TokenCappedCrowdsale * @dev Crowdsale with a limit for total minted tokens. */ contract TokenCappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public tokenCap = 0; // Amount of LPC raised uint256 public tokensRaised = 0; // event for manual refund of cap overflow event CapOverflow(address indexed sender, uint256 weiAmount, uint256 receivedTokens, uint256 date); /** * Checks whether the tokenCap has been reached. * @return Whether the tokenCap was reached */ function capReached() public view returns (bool) { return tokensRaised >= tokenCap; } /** * Accumulate the purchased tokens to the total raised */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); super._updatePurchasingState(_beneficiary, _weiAmount); uint256 purchasedTokens = _getTokenAmount(_weiAmount); tokensRaised = tokensRaised.add(purchasedTokens); if(capReached()) { // manual process unused eth amount to sender emit CapOverflow(_beneficiary, _weiAmount, purchasedTokens, now); } } } /** * @title TieredCrowdsale * @dev Extension of Crowdsale contract that decreases the number of LPC tokens purchases dependent on the current number of tokens sold. */ contract TieredCrowdsale is TokenCappedCrowdsale, Ownable { using SafeMath for uint256; /** SalesState enum for use in state machine to manage sales rates */ enum SaleState { Initial, // All contract initialization calls PrivateSale, // Private sale for industy and closed group investors FinalisedPrivateSale, // Close private sale PreSale, // Pre sale ICO (40% bonus LPC hard-capped at 180 million tokens) FinalisedPreSale, // Close presale PublicSaleTier1, // Tier 1 ICO public sale (30% bonus LPC capped at 85 million tokens) PublicSaleTier2, // Tier 2 ICO public sale (20% bonus LPC capped at 65 million tokens) PublicSaleTier3, // Tier 3 ICO public sale (10% bonus LPC capped at 45 million tokens) PublicSaleTier4, // Tier 4 ICO public sale (standard rate capped at 25 million tokens) FinalisedPublicSale, // Close public sale Closed // ICO has finished, all tokens must have been claimed } SaleState public state = SaleState.Initial; struct TierConfig { string stateName; uint256 tierRatePercentage; uint256 hardCap; } mapping(bytes32 => TierConfig) private tierConfigs; // event for manual refund of cap overflow event IncrementTieredState(string stateName); /** * checks the state when validating a purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); super._preValidatePurchase(_beneficiary, _weiAmount); require( state == SaleState.PrivateSale || state == SaleState.PreSale || state == SaleState.PublicSaleTier1 || state == SaleState.PublicSaleTier2 || state == SaleState.PublicSaleTier3 || state == SaleState.PublicSaleTier4 ); } /** * @dev Constructor * Caveat emptor: this base contract is intended for inheritance by the Little Phil crowdsale only */ constructor() public { // setup the map of bonus-rates for each SaleState tier createSalesTierConfigMap(); } /** * @dev Overrides parent method taking into account variable rate (as a percentage). * @param _weiAmount The value in wei to be converted into tokens * @return The number of tokens _weiAmount wei will buy at present time. */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentTierRate = getCurrentTierRatePercentage(); uint256 requestedTokenAmount = _weiAmount.mul(rate).mul(currentTierRate).div(100); uint256 remainingTokens = tokenCap.sub(tokensRaised); // return number of LPC to provide if(requestedTokenAmount > remainingTokens ) { return remainingTokens; } return requestedTokenAmount; } /** * @dev setup the map of bonus-rates (as a percentage) and total hardCap for each SaleState tier * to be called by the constructor. */ function createSalesTierConfigMap() private { tierConfigs [keccak256(SaleState.Initial)] = TierConfig({ stateName: "Initial", tierRatePercentage:0, hardCap: 0 }); tierConfigs [keccak256(SaleState.PrivateSale)] = TierConfig({ stateName: "PrivateSale", tierRatePercentage:100, hardCap: SafeMath.mul(400000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.FinalisedPrivateSale)] = TierConfig({ stateName: "FinalisedPrivateSale", tierRatePercentage:0, hardCap: 0 }); tierConfigs [keccak256(SaleState.PreSale)] = TierConfig({ stateName: "PreSale", tierRatePercentage:140, hardCap: SafeMath.mul(180000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.FinalisedPreSale)] = TierConfig({ stateName: "FinalisedPreSale", tierRatePercentage:0, hardCap: 0 }); tierConfigs [keccak256(SaleState.PublicSaleTier1)] = TierConfig({ stateName: "PublicSaleTier1", tierRatePercentage:130, hardCap: SafeMath.mul(265000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.PublicSaleTier2)] = TierConfig({ stateName: "PublicSaleTier2", tierRatePercentage:120, hardCap: SafeMath.mul(330000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.PublicSaleTier3)] = TierConfig({ stateName: "PublicSaleTier3", tierRatePercentage:110, hardCap: SafeMath.mul(375000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.PublicSaleTier4)] = TierConfig({ stateName: "PublicSaleTier4", tierRatePercentage:100, hardCap: SafeMath.mul(400000000, (10 ** 18)) }); tierConfigs [keccak256(SaleState.FinalisedPublicSale)] = TierConfig({ stateName: "FinalisedPublicSale", tierRatePercentage:0, hardCap: 0 }); tierConfigs [keccak256(SaleState.Closed)] = TierConfig({ stateName: "Closed", tierRatePercentage:0, hardCap: SafeMath.mul(400000000, (10 ** 18)) }); } /** * @dev get the current bonus-rate for the current SaleState * @return the current rate as a percentage (e.g. 140 = 140% bonus) */ function getCurrentTierRatePercentage() public view returns (uint256) { return tierConfigs[keccak256(state)].tierRatePercentage; } /** * @dev get the current hardCap for the current SaleState * @return the current hardCap */ function getCurrentTierHardcap() public view returns (uint256) { return tierConfigs[keccak256(state)].hardCap; } /** * @dev only allow the owner to modify the current SaleState */ function setState(uint256 _state) onlyOwner public { state = SaleState(_state); // update cap when state changes tokenCap = getCurrentTierHardcap(); if(state == SaleState.Closed) { crowdsaleClosed(); } } function getState() public view returns (string) { return tierConfigs[keccak256(state)].stateName; } /** * @dev only allow onwer to modify the current SaleState */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); super._updatePurchasingState(_beneficiary, _weiAmount); if(capReached()) { if(state == SaleState.PrivateSale) { state = SaleState.FinalisedPrivateSale; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } else if(state == SaleState.PreSale) { state = SaleState.FinalisedPreSale; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } else if(state == SaleState.PublicSaleTier1) { state = SaleState.PublicSaleTier2; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } else if(state == SaleState.PublicSaleTier2) { state = SaleState.PublicSaleTier3; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } else if(state == SaleState.PublicSaleTier3) { state = SaleState.PublicSaleTier4; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } else if(state == SaleState.PublicSaleTier4) { state = SaleState.FinalisedPublicSale; tokenCap = getCurrentTierHardcap(); emit IncrementTieredState(getState()); } } } /** * Override for extensions that require an internal notification when the crowdsale has closed */ function crowdsaleClosed () internal { // optional override } } /* solium-disable security/no-block-members */ /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract TokenVestingCrowdsale is Crowdsale, Ownable { function addBeneficiaryVestor( address beneficiaryWallet, uint256 tokenAmount, uint256 vestingEpocStart, uint256 cliffInSeconds, uint256 vestingEpocEnd ) external onlyOwner { TokenVesting newVault = new TokenVesting( beneficiaryWallet, vestingEpocStart, cliffInSeconds, vestingEpocEnd, false ); LittlePhilCoin(token).mint(address(newVault), tokenAmount); } function releaseVestingTokens(address vaultAddress) external onlyOwner { TokenVesting(vaultAddress).release(token); } } contract LittlePhilCrowdsale is MintedCrowdsale, TieredCrowdsale, InitialSupplyCrowdsale, WhitelistedCrowdsale, TokenVestingCrowdsale { /** * Event for rate-change logging * @param rate the new ETH-to_LPC exchange rate */ event NewRate(uint256 rate); // Constructor constructor( uint256 _rate, address _fundsWallet, address[6] _wallets, LittlePhilCoin _token ) public Crowdsale(_rate, _fundsWallet, _token) InitialSupplyCrowdsale(_wallets) {} // Sets up the initial balances // This must be called after ownership of the token is transferred to the crowdsale function setupInitialState() external onlyOwner { setupInitialSupply(); } // Ownership management function transferTokenOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0)); // I assume the crowdsale contract holds a reference to the token contract. LittlePhilCoin(token).transferOwnership(_newOwner); } // Called at the end of the crowdsale when it is eneded function crowdsaleClosed () internal { uint256 remainingTokens = tokenCap.sub(tokensRaised); _deliverTokens(airdropWallet, remainingTokens); LittlePhilCoin(token).finishMinting(); } /** * checks the state when validating a purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); super._preValidatePurchase(_beneficiary, _weiAmount); require(_weiAmount >= 500000000000000000); } /** * @dev sets (updates) the ETH-to-LPC exchange rate * @param _rate ate that will applied to ETH to derive how many LPC to mint * does not affect, nor influenced by the bonus rates based on the current tier. */ function setRate(int _rate) public onlyOwner { require(_rate > 0); rate = uint256(_rate); emit NewRate(rate); } /** * @dev allows for minting from owner account */ function mintForPrivateFiat(address _beneficiary, uint256 _weiAmount) public onlyOwner { require(_beneficiary != address(0)); // require(_weiAmount > 0); _preValidatePurchase(_beneficiary, _weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(_weiAmount); // update state weiRaised = weiRaised.add(_weiAmount); tokensRaised = tokensRaised.add(tokens); if(capReached()) { // manual process unused eth amount to sender emit CapOverflow(_beneficiary, _weiAmount, tokens, now); emit IncrementTieredState(getState()); } _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, _weiAmount, tokens ); _updatePurchasingState(_beneficiary, _weiAmount); _forwardFunds(); } }
checks the state when validating a purchase/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); super._preValidatePurchase(_beneficiary, _weiAmount); require(_weiAmount >= 500000000000000000); }
6,264,765
./full_match/43114/0x78F48e2e68A7C09E22fBa362C0FccA51b4772683/sources/IglooMasterV7.10_Strategies.sol
set your own personal xpefiDistributionBipstrack if user has ever set their own xpefiDistributionBips
function setXpefiDistributionBips(uint256 _xpefiDistributionBips) external { require(_xpefiDistributionBips <= MAX_BIPS, "input too high"); if (!xpefiDistributionBipsSet[msg.sender]) { xpefiDistributionBipsSet[msg.sender] = true; } xpefiDistributionBips[msg.sender] = _xpefiDistributionBips; }
4,505,953
./full_match/11155111/0x7DAB44b642cE9c008b5E0c1a9240236cB67481C6/sources/contracts/BloodDonation.sol
Function to add a new organization _adminAddress The address of an admin/
function addOrganization(address _adminAddress) public { require(msg.sender == _isAdmin, "Only admin can add organization"); _isOrganization[_adminAddress] = true; }
3,801,507
./full_match/421613/0xc3A8621DA59B35dDCD3e01504F182D9AC9F36b5B/sources/src/arbitration/SortitionModule.sol
Executes the next delayed stakes. _iterations The number of delayed stakes to execute.
function executeDelayedStakes(uint256 _iterations) external { require(phase == Phase.staking, "Should be in Staking phase."); uint256 actualIterations = (delayedStakeReadIndex + _iterations) - 1 > delayedStakeWriteIndex ? (delayedStakeWriteIndex - delayedStakeReadIndex) + 1 : _iterations; uint256 newDelayedStakeReadIndex = delayedStakeReadIndex + actualIterations; for (uint256 i = delayedStakeReadIndex; i < newDelayedStakeReadIndex; i++) { DelayedStake storage delayedStake = delayedStakes[i]; core.setStakeBySortitionModule( delayedStake.account, delayedStake.courtID, delayedStake.stake, delayedStake.penalty ); delete delayedStakes[i]; } delayedStakeReadIndex = newDelayedStakeReadIndex; }
11,570,386
./partial_match/1/0x8770B2a109AEE8CDbe278FaE6CaE5Aa4Bcd13E1c/sources/Users/ryanbreen/Workspace/Alkemi/alkemi-earn/alkemi-earn-protocol/contracts/TestTokens.sol
How much has the owner delegated/approved to the delegate
function allowance(address owner, address delegate) external view returns (uint){ return allowed[owner][delegate]; }
3,595,631
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.8.10; import {ILensHub} from '../interfaces/ILensHub.sol'; import {Events} from '../libraries/Events.sol'; import {Helpers} from '../libraries/Helpers.sol'; import {Constants} from '../libraries/Constants.sol'; import {DataTypes} from '../libraries/DataTypes.sol'; import {Errors} from '../libraries/Errors.sol'; import {PublishingLogic} from '../libraries/PublishingLogic.sol'; import {ProfileTokenURILogic} from '../libraries/ProfileTokenURILogic.sol'; import {InteractionLogic} from '../libraries/InteractionLogic.sol'; import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import {LensNFTBase} from './base/LensNFTBase.sol'; import {LensMultiState} from './base/LensMultiState.sol'; import {LensHubStorage} from './storage/LensHubStorage.sol'; import {VersionedInitializable} from '../upgradeability/VersionedInitializable.sol'; /** * @title LensHub * @author Lens Protocol * * @notice This is the main entrypoint of the Lens Protocol. It contains governance functionality as well as * publishing and profile interaction functionality. * * NOTE: The Lens Protocol is unique in that frontend operators need to track a potentially overwhelming * number of NFT contracts and interactions at once. For that reason, we've made two quirky design decisions: * 1. Both Follow & Collect NFTs invoke an LensHub callback on transfer with the sole purpose of emitting an event. * 2. Almost every event in the protocol emits the current block timestamp, reducing the need to fetch it manually. */ contract LensHub is ILensHub, LensNFTBase, VersionedInitializable, LensMultiState, LensHubStorage { uint256 internal constant REVISION = 1; address internal immutable FOLLOW_NFT_IMPL; address internal immutable COLLECT_NFT_IMPL; /** * @dev This modifier reverts if the caller is not the configured governance address. */ modifier onlyGov() { _validateCallerIsGovernance(); _; } /** * @dev This modifier reverts if the caller is not a whitelisted profile creator address. */ modifier onlyWhitelistedProfileCreator() { _validateCallerIsWhitelistedProfileCreator(); _; } /** * @dev The constructor sets the immutable follow & collect NFT implementations. * * @param followNFTImpl The follow NFT implementation address. * @param collectNFTImpl The collect NFT implementation address. */ constructor(address followNFTImpl, address collectNFTImpl) { FOLLOW_NFT_IMPL = followNFTImpl; COLLECT_NFT_IMPL = collectNFTImpl; } /// @inheritdoc ILensHub function initialize( string calldata name, string calldata symbol, address newGovernance ) external override initializer { super._initialize(name, symbol); _setState(DataTypes.ProtocolState.Paused); _setGovernance(newGovernance); } /// *********************** /// *****GOV FUNCTIONS***** /// *********************** /// @inheritdoc ILensHub function setGovernance(address newGovernance) external override onlyGov { _setGovernance(newGovernance); } /// @inheritdoc ILensHub function setEmergencyAdmin(address newEmergencyAdmin) external override onlyGov { address prevEmergencyAdmin = _emergencyAdmin; _emergencyAdmin = newEmergencyAdmin; emit Events.EmergencyAdminSet( msg.sender, prevEmergencyAdmin, newEmergencyAdmin, block.timestamp ); } /// @inheritdoc ILensHub function setState(DataTypes.ProtocolState newState) external override { if (msg.sender != _governance && msg.sender != _emergencyAdmin) revert Errors.NotGovernanceOrEmergencyAdmin(); _setState(newState); } ///@inheritdoc ILensHub function whitelistProfileCreator(address profileCreator, bool whitelist) external override onlyGov { _profileCreatorWhitelisted[profileCreator] = whitelist; emit Events.ProfileCreatorWhitelisted(profileCreator, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistFollowModule(address followModule, bool whitelist) external override onlyGov { _followModuleWhitelisted[followModule] = whitelist; emit Events.FollowModuleWhitelisted(followModule, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistReferenceModule(address referenceModule, bool whitelist) external override onlyGov { _referenceModuleWhitelisted[referenceModule] = whitelist; emit Events.ReferenceModuleWhitelisted(referenceModule, whitelist, block.timestamp); } /// @inheritdoc ILensHub function whitelistCollectModule(address collectModule, bool whitelist) external override onlyGov { _collectModuleWhitelisted[collectModule] = whitelist; emit Events.CollectModuleWhitelisted(collectModule, whitelist, block.timestamp); } /// ********************************* /// *****PROFILE OWNER FUNCTIONS***** /// ********************************* /// @inheritdoc ILensHub function createProfile(DataTypes.CreateProfileData calldata vars) external override whenNotPaused onlyWhitelistedProfileCreator { uint256 profileId = ++_profileCounter; _mint(vars.to, profileId); PublishingLogic.createProfile( vars, profileId, _profileIdByHandleHash, _profileById, _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setDefaultProfile(uint256 profileId) external override whenNotPaused { _setDefaultProfile(msg.sender, profileId); } /// @inheritdoc ILensHub function setDefaultProfileWithSig(DataTypes.SetDefaultProfileWithSigData calldata vars) external override whenNotPaused { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_DEFAULT_PROFILE_WITH_SIG_TYPEHASH, vars.wallet, vars.profileId, sigNonces[vars.wallet]++, vars.sig.deadline ) ) ), vars.wallet, vars.sig ); _setDefaultProfile(vars.wallet, vars.profileId); } /// @inheritdoc ILensHub function setFollowModule( uint256 profileId, address followModule, bytes calldata followModuleData ) external override whenNotPaused { _validateCallerIsProfileOwner(profileId); PublishingLogic.setFollowModule( profileId, followModule, followModuleData, _profileById[profileId], _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setFollowModuleWithSig(DataTypes.SetFollowModuleWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_FOLLOW_MODULE_WITH_SIG_TYPEHASH, vars.profileId, vars.followModule, keccak256(vars.followModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); PublishingLogic.setFollowModule( vars.profileId, vars.followModule, vars.followModuleData, _profileById[vars.profileId], _followModuleWhitelisted ); } /// @inheritdoc ILensHub function setDispatcher(uint256 profileId, address dispatcher) external override whenNotPaused { _validateCallerIsProfileOwner(profileId); _setDispatcher(profileId, dispatcher); } /// @inheritdoc ILensHub function setDispatcherWithSig(DataTypes.SetDispatcherWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_DISPATCHER_WITH_SIG_TYPEHASH, vars.profileId, vars.dispatcher, sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setDispatcher(vars.profileId, vars.dispatcher); } /// @inheritdoc ILensHub function setProfileImageURI(uint256 profileId, string calldata imageURI) external override whenNotPaused { _validateCallerIsProfileOwnerOrDispatcher(profileId); _setProfileImageURI(profileId, imageURI); } /// @inheritdoc ILensHub function setProfileImageURIWithSig(DataTypes.SetProfileImageURIWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_PROFILE_IMAGE_URI_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.imageURI)), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setProfileImageURI(vars.profileId, vars.imageURI); } /// @inheritdoc ILensHub function setFollowNFTURI(uint256 profileId, string calldata followNFTURI) external override whenNotPaused { _validateCallerIsProfileOwnerOrDispatcher(profileId); _setFollowNFTURI(profileId, followNFTURI); } /// @inheritdoc ILensHub function setFollowNFTURIWithSig(DataTypes.SetFollowNFTURIWithSigData calldata vars) external override whenNotPaused { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( SET_FOLLOW_NFT_URI_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.followNFTURI)), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _setFollowNFTURI(vars.profileId, vars.followNFTURI); } /// @inheritdoc ILensHub function post(DataTypes.PostData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createPost( vars.profileId, vars.contentURI, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function postWithSig(DataTypes.PostWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( POST_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.contentURI)), vars.collectModule, keccak256(vars.collectModuleData), vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createPost( vars.profileId, vars.contentURI, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function comment(DataTypes.CommentData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createComment(vars); } /// @inheritdoc ILensHub function commentWithSig(DataTypes.CommentWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( COMMENT_WITH_SIG_TYPEHASH, vars.profileId, keccak256(bytes(vars.contentURI)), vars.profileIdPointed, vars.pubIdPointed, vars.collectModule, keccak256(vars.collectModuleData), vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createComment( DataTypes.CommentData( vars.profileId, vars.contentURI, vars.profileIdPointed, vars.pubIdPointed, vars.collectModule, vars.collectModuleData, vars.referenceModule, vars.referenceModuleData ) ); } /// @inheritdoc ILensHub function mirror(DataTypes.MirrorData calldata vars) external override whenPublishingEnabled { _validateCallerIsProfileOwnerOrDispatcher(vars.profileId); _createMirror( vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, vars.referenceModuleData ); } /// @inheritdoc ILensHub function mirrorWithSig(DataTypes.MirrorWithSigData calldata vars) external override whenPublishingEnabled { address owner = ownerOf(vars.profileId); _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( MIRROR_WITH_SIG_TYPEHASH, vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, keccak256(vars.referenceModuleData), sigNonces[owner]++, vars.sig.deadline ) ) ), owner, vars.sig ); _createMirror( vars.profileId, vars.profileIdPointed, vars.pubIdPointed, vars.referenceModule, vars.referenceModuleData ); } /** * @notice Burns a profile, this maintains the profile data struct, but deletes the * handle hash to profile ID mapping value. * * NOTE: This overrides the LensNFTBase contract's `burn()` function and calls it to fully burn * the NFT. */ function burn(uint256 tokenId) public override whenNotPaused { super.burn(tokenId); _clearHandleHash(tokenId); } /** * @notice Burns a profile with a signature, this maintains the profile data struct, but deletes the * handle hash to profile ID mapping value. * * NOTE: This overrides the LensNFTBase contract's `burnWithSig()` function and calls it to fully burn * the NFT. */ function burnWithSig(uint256 tokenId, DataTypes.EIP712Signature calldata sig) public override whenNotPaused { super.burnWithSig(tokenId, sig); _clearHandleHash(tokenId); } /// *************************************** /// *****PROFILE INTERACTION FUNCTIONS***** /// *************************************** /// @inheritdoc ILensHub function follow(uint256[] calldata profileIds, bytes[] calldata datas) external override whenNotPaused { InteractionLogic.follow( msg.sender, profileIds, datas, FOLLOW_NFT_IMPL, _profileById, _profileIdByHandleHash ); } /// @inheritdoc ILensHub function followWithSig(DataTypes.FollowWithSigData calldata vars) external override whenNotPaused { bytes32[] memory dataHashes = new bytes32[](vars.datas.length); for (uint256 i = 0; i < vars.datas.length; ++i) { dataHashes[i] = keccak256(vars.datas[i]); } _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( FOLLOW_WITH_SIG_TYPEHASH, keccak256(abi.encodePacked(vars.profileIds)), keccak256(abi.encodePacked(dataHashes)), sigNonces[vars.follower]++, vars.sig.deadline ) ) ), vars.follower, vars.sig ); InteractionLogic.follow( vars.follower, vars.profileIds, vars.datas, FOLLOW_NFT_IMPL, _profileById, _profileIdByHandleHash ); } /// @inheritdoc ILensHub function collect( uint256 profileId, uint256 pubId, bytes calldata data ) external override whenNotPaused { InteractionLogic.collect( msg.sender, profileId, pubId, data, COLLECT_NFT_IMPL, _pubByIdByProfile, _profileById ); } /// @inheritdoc ILensHub function collectWithSig(DataTypes.CollectWithSigData calldata vars) external override whenNotPaused { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( COLLECT_WITH_SIG_TYPEHASH, vars.profileId, vars.pubId, keccak256(vars.data), sigNonces[vars.collector]++, vars.sig.deadline ) ) ), vars.collector, vars.sig ); InteractionLogic.collect( vars.collector, vars.profileId, vars.pubId, vars.data, COLLECT_NFT_IMPL, _pubByIdByProfile, _profileById ); } /// @inheritdoc ILensHub function emitFollowNFTTransferEvent( uint256 profileId, uint256 followNFTId, address from, address to ) external override { address expectedFollowNFT = _profileById[profileId].followNFT; if (msg.sender != expectedFollowNFT) revert Errors.CallerNotFollowNFT(); emit Events.FollowNFTTransferred(profileId, followNFTId, from, to, block.timestamp); } /// @inheritdoc ILensHub function emitCollectNFTTransferEvent( uint256 profileId, uint256 pubId, uint256 collectNFTId, address from, address to ) external override { address expectedCollectNFT = _pubByIdByProfile[profileId][pubId].collectNFT; if (msg.sender != expectedCollectNFT) revert Errors.CallerNotCollectNFT(); emit Events.CollectNFTTransferred( profileId, pubId, collectNFTId, from, to, block.timestamp ); } /// ********************************* /// *****EXTERNAL VIEW FUNCTIONS***** /// ********************************* /// @inheritdoc ILensHub function isProfileCreatorWhitelisted(address profileCreator) external view override returns (bool) { return _profileCreatorWhitelisted[profileCreator]; } /// @inheritdoc ILensHub function defaultProfile(address wallet) external view override returns (uint256) { return _defaultProfileByAddress[wallet]; } /// @inheritdoc ILensHub function isFollowModuleWhitelisted(address followModule) external view override returns (bool) { return _followModuleWhitelisted[followModule]; } /// @inheritdoc ILensHub function isReferenceModuleWhitelisted(address referenceModule) external view override returns (bool) { return _referenceModuleWhitelisted[referenceModule]; } /// @inheritdoc ILensHub function isCollectModuleWhitelisted(address collectModule) external view override returns (bool) { return _collectModuleWhitelisted[collectModule]; } /// @inheritdoc ILensHub function getGovernance() external view override returns (address) { return _governance; } /// @inheritdoc ILensHub function getDispatcher(uint256 profileId) external view override returns (address) { return _dispatcherByProfile[profileId]; } /// @inheritdoc ILensHub function getPubCount(uint256 profileId) external view override returns (uint256) { return _profileById[profileId].pubCount; } /// @inheritdoc ILensHub function getFollowNFT(uint256 profileId) external view override returns (address) { return _profileById[profileId].followNFT; } /// @inheritdoc ILensHub function getFollowNFTURI(uint256 profileId) external view override returns (string memory) { return _profileById[profileId].followNFTURI; } /// @inheritdoc ILensHub function getCollectNFT(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].collectNFT; } /// @inheritdoc ILensHub function getFollowModule(uint256 profileId) external view override returns (address) { return _profileById[profileId].followModule; } /// @inheritdoc ILensHub function getCollectModule(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].collectModule; } /// @inheritdoc ILensHub function getReferenceModule(uint256 profileId, uint256 pubId) external view override returns (address) { return _pubByIdByProfile[profileId][pubId].referenceModule; } /// @inheritdoc ILensHub function getHandle(uint256 profileId) external view override returns (string memory) { return _profileById[profileId].handle; } /// @inheritdoc ILensHub function getPubPointer(uint256 profileId, uint256 pubId) external view override returns (uint256, uint256) { uint256 profileIdPointed = _pubByIdByProfile[profileId][pubId].profileIdPointed; uint256 pubIdPointed = _pubByIdByProfile[profileId][pubId].pubIdPointed; return (profileIdPointed, pubIdPointed); } /// @inheritdoc ILensHub function getContentURI(uint256 profileId, uint256 pubId) external view override returns (string memory) { (uint256 rootProfileId, uint256 rootPubId, ) = Helpers.getPointedIfMirror( profileId, pubId, _pubByIdByProfile ); return _pubByIdByProfile[rootProfileId][rootPubId].contentURI; } /// @inheritdoc ILensHub function getProfileIdByHandle(string calldata handle) external view override returns (uint256) { bytes32 handleHash = keccak256(bytes(handle)); return _profileIdByHandleHash[handleHash]; } /// @inheritdoc ILensHub function getProfile(uint256 profileId) external view override returns (DataTypes.ProfileStruct memory) { return _profileById[profileId]; } /// @inheritdoc ILensHub function getPub(uint256 profileId, uint256 pubId) external view override returns (DataTypes.PublicationStruct memory) { return _pubByIdByProfile[profileId][pubId]; } /// @inheritdoc ILensHub function getPubType(uint256 profileId, uint256 pubId) external view override returns (DataTypes.PubType) { if (pubId == 0 || _profileById[profileId].pubCount < pubId) { return DataTypes.PubType.Nonexistent; } else if (_pubByIdByProfile[profileId][pubId].collectModule == address(0)) { return DataTypes.PubType.Mirror; } else { if (_pubByIdByProfile[profileId][pubId].profileIdPointed == 0) { return DataTypes.PubType.Post; } else { return DataTypes.PubType.Comment; } } } /** * @dev Overrides the ERC721 tokenURI function to return the associated URI with a given profile. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { address followNFT = _profileById[tokenId].followNFT; return ProfileTokenURILogic.getProfileTokenURI( tokenId, followNFT == address(0) ? 0 : IERC721Enumerable(followNFT).totalSupply(), ownerOf(tokenId), _profileById[tokenId].handle, _profileById[tokenId].imageURI ); } /// **************************** /// *****INTERNAL FUNCTIONS***** /// **************************** function _setGovernance(address newGovernance) internal { address prevGovernance = _governance; _governance = newGovernance; emit Events.GovernanceSet(msg.sender, prevGovernance, newGovernance, block.timestamp); } function _createPost( uint256 profileId, string memory contentURI, address collectModule, bytes memory collectModuleData, address referenceModule, bytes memory referenceModuleData ) internal { PublishingLogic.createPost( profileId, contentURI, collectModule, collectModuleData, referenceModule, referenceModuleData, ++_profileById[profileId].pubCount, _pubByIdByProfile, _collectModuleWhitelisted, _referenceModuleWhitelisted ); } function _setDefaultProfile(address wallet, uint256 profileId) internal { if (profileId > 0) { if (wallet != ownerOf(profileId)) revert Errors.NotProfileOwner(); } _defaultProfileByAddress[wallet] = profileId; emit Events.DefaultProfileSet(wallet, profileId, block.timestamp); } function _createComment(DataTypes.CommentData memory vars) internal { PublishingLogic.createComment( vars, _profileById[vars.profileId].pubCount + 1, _profileById, _pubByIdByProfile, _collectModuleWhitelisted, _referenceModuleWhitelisted ); _profileById[vars.profileId].pubCount++; } function _createMirror( uint256 profileId, uint256 profileIdPointed, uint256 pubIdPointed, address referenceModule, bytes calldata referenceModuleData ) internal { PublishingLogic.createMirror( profileId, profileIdPointed, pubIdPointed, referenceModule, referenceModuleData, ++_profileById[profileId].pubCount, _pubByIdByProfile, _referenceModuleWhitelisted ); } function _setDispatcher(uint256 profileId, address dispatcher) internal { _dispatcherByProfile[profileId] = dispatcher; emit Events.DispatcherSet(profileId, dispatcher, block.timestamp); } function _setProfileImageURI(uint256 profileId, string memory imageURI) internal { if (bytes(imageURI).length > Constants.MAX_PROFILE_IMAGE_URI_LENGTH) revert Errors.ProfileImageURILengthInvalid(); _profileById[profileId].imageURI = imageURI; emit Events.ProfileImageURISet(profileId, imageURI, block.timestamp); } function _setFollowNFTURI(uint256 profileId, string memory followNFTURI) internal { _profileById[profileId].followNFTURI = followNFTURI; emit Events.FollowNFTURISet(profileId, followNFTURI, block.timestamp); } function _clearHandleHash(uint256 profileId) internal { bytes32 handleHash = keccak256(bytes(_profileById[profileId].handle)); _profileIdByHandleHash[handleHash] = 0; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override whenNotPaused { if (_dispatcherByProfile[tokenId] != address(0)) { _setDispatcher(tokenId, address(0)); } if (_defaultProfileByAddress[from] == tokenId) { _defaultProfileByAddress[from] = 0; } super._beforeTokenTransfer(from, to, tokenId); } function _validateCallerIsProfileOwnerOrDispatcher(uint256 profileId) internal view { if (msg.sender != ownerOf(profileId) && msg.sender != _dispatcherByProfile[profileId]) revert Errors.NotProfileOwnerOrDispatcher(); } function _validateCallerIsProfileOwner(uint256 profileId) internal view { if (msg.sender != ownerOf(profileId)) revert Errors.NotProfileOwner(); } function _validateCallerIsGovernance() internal view { if (msg.sender != _governance) revert Errors.NotGovernance(); } function _validateCallerIsWhitelistedProfileCreator() internal view { if (!_profileCreatorWhitelisted[msg.sender]) revert Errors.ProfileCreatorNotWhitelisted(); } function getRevision() internal pure virtual override returns (uint256) { return REVISION; } }
@inheritdoc ILensHub
function collectWithSig(DataTypes.CollectWithSigData calldata vars) external override whenNotPaused { _validateRecoveredAddress( _calculateDigest( keccak256( abi.encode( COLLECT_WITH_SIG_TYPEHASH, vars.profileId, vars.pubId, keccak256(vars.data), sigNonces[vars.collector]++, vars.sig.deadline ) ) ), vars.collector, vars.sig ); InteractionLogic.collect( vars.collector, vars.profileId, vars.pubId, vars.data, COLLECT_NFT_IMPL, _pubByIdByProfile, _profileById ); }
12,861,967
./partial_match/1/0x1111111254EEB25477B68fb85Ed929f73A960582/sources/AggregationRouterV5.sol
If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry
function forceApprove(IERC20 token, address spender, uint256 value) internal { if (!_makeCall(token, token.approve.selector, spender, value)) { if (!_makeCall(token, token.approve.selector, spender, 0) || !_makeCall(token, token.approve.selector, spender, value)) { revert ForceApproveFailed(); } } if (!_makeCall(token, token.approve.selector, spender, value)) { if (!_makeCall(token, token.approve.selector, spender, 0) || !_makeCall(token, token.approve.selector, spender, value)) { revert ForceApproveFailed(); } } }
9,171,629
pragma solidity ^0.4.25; /** .----------------. .----------------. .----------------. .----------------. | .--------------. || .--------------. || .--------------. || .--------------. | | | ____ ____ | || | ____ | || | _____ | || | ________ | | | | |_ || _| | || | .' `. | || | |_ _| | || | |_ ___ `. | | | | | |__| | | || | / .--. \ | || | | | | || | | | `. \ | | | | | __ | | || | | | | | | || | | | _ | || | | | | | | | | | _| | | |_ | || | \ `--' / | || | _| |__/ | | || | _| |___.' / | | | | |____||____| | || | `.____.' | || | |________| | || | |________.' | | | | | || | | || | | || | | | | '--------------' || '--------------' || '--------------' || '--------------' | '----------------' '----------------' '----------------' '----------------' **/ /*============================== = Version 8.1 = ==============================*/ contract EthereumSmartContract { address EthereumNodes; constructor() public { EthereumNodes = msg.sender; } modifier restricted() { require(msg.sender == EthereumNodes); _; } function GetEthereumNodes() public view returns (address owner) { return EthereumNodes; } } contract ldoh is EthereumSmartContract { /*============================== = EVENTS = ==============================*/ event onCashbackCode (address indexed hodler, address cashbackcode); event onAffiliateBonus (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onHoldplatform (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onUnlocktoken (address indexed hodler, address indexed tokenAddress, string tokenSymbol, uint256 amount, uint256 endtime); event onReceiveAirdrop (address indexed hodler, uint256 amount, uint256 datetime); event onHOLDdeposit (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); event onHOLDwithdraw (address indexed hodler, uint256 amount, uint256 newbalance, uint256 datetime); /*============================== = VARIABLES = ==============================*/ //-------o Affiliate = 12% o-------o Cashback = 16% o-------o Total Receive = 88% o-------o Without Cashback = 72% o-------o //-------o Hold 24 Months, Unlock 3% Permonth // Struct Database struct Safe { uint256 id; // [01] -- > Registration Number uint256 amount; // [02] -- > Total amount of contribution to this transaction uint256 endtime; // [03] -- > The Expiration Of A Hold Platform Based On Unix Time address user; // [04] -- > The ETH address that you are using address tokenAddress; // [05] -- > The Token Contract Address That You Are Using string tokenSymbol; // [06] -- > The Token Symbol That You Are Using uint256 amountbalance; // [07] -- > 88% from Contribution / 72% Without Cashback uint256 cashbackbalance; // [08] -- > 16% from Contribution / 0% Without Cashback uint256 lasttime; // [09] -- > The Last Time You Withdraw Based On Unix Time uint256 percentage; // [10] -- > The percentage of tokens that are unlocked every month ( Default = 3% ) uint256 percentagereceive; // [11] -- > The Percentage You Have Received uint256 tokenreceive; // [12] -- > The Number Of Tokens You Have Received uint256 lastwithdraw; // [13] -- > The Last Amount You Withdraw address referrer; // [14] -- > Your ETH referrer address bool cashbackstatus; // [15] -- > Cashback Status } uint256 private idnumber; // [01] -- > ID number ( Start from 500 ) uint256 public TotalUser; // [02] -- > Total Smart Contract User mapping(address => address) public cashbackcode; // [03] -- > Cashback Code mapping(address => uint256[]) public idaddress; // [04] -- > Search Address by ID mapping(address => address[]) public afflist; // [05] -- > Affiliate List by ID mapping(address => string) public ContractSymbol; // [06] -- > Contract Address Symbol mapping(uint256 => Safe) private _safes; // [07] -- > Struct safe database mapping(address => bool) public contractaddress; // [08] -- > Contract Address mapping (address => mapping (uint256 => uint256)) public Bigdata; /** Bigdata Mapping : [1] Percent (Monthly Unlocked tokens) [7] All Payments [13] Total TX Affiliate (Withdraw) [2] Holding Time (in seconds) [8] Active User [14] Current Price (USD) [3] Token Balance [9] Total User [15] ATH Price (USD) [4] Min Contribution [10] Total TX Hold [16] ATL Price (USD) [5] Max Contribution [11] Total TX Unlock [17] Current ETH Price (ETH) [6] All Contribution [12] Total TX Airdrop [18] Unique Code **/ mapping (address => mapping (address => mapping (uint256 => uint256))) public Statistics; // Statistics = [1] LifetimeContribution [2] LifetimePayments [3] Affiliatevault [4] Affiliateprofit [5] ActiveContribution // Airdrop - Hold Platform (HOLD) address public Holdplatform_address; // [01] uint256 public Holdplatform_balance; // [02] mapping(address => uint256) private Holdplatform_status; // [03] mapping(address => uint256) private Holdplatform_divider; // [04] /*============================== = CONSTRUCTOR = ==============================*/ constructor() public { idnumber = 500; Holdplatform_address = 0x23bAdee11Bf49c40669e9b09035f048e9146213e; //Change before deploy } /*============================== = AVAILABLE FOR EVERYONE = ==============================*/ //-------o Function 01 - Ethereum Payable function () public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothemoon() public payable { if (msg.value == 0) { tothe_moon(); } else { revert(); } } function tothe_moon() private { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.user == msg.sender) { Unlocktoken(s.tokenAddress, s.id); } } } //-------o Function 02 - Cashback Code function CashbackCode(address _cashbackcode, uint256 uniquecode) public { require(_cashbackcode != msg.sender); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 && Bigdata[_cashbackcode][8] >= 1 && Bigdata[_cashbackcode][18] != uniquecode ) { cashbackcode[msg.sender] = _cashbackcode; } else { cashbackcode[msg.sender] = EthereumNodes; } if (Bigdata[msg.sender][18] == 0 ) { Bigdata[msg.sender][18] = uniquecode; } emit onCashbackCode(msg.sender, _cashbackcode); } //-------o Function 03 - Contribute //--o 01 function Holdplatform(address tokenAddress, uint256 amount) public { require(amount >= 1 ); uint256 holdamount = add(Statistics[msg.sender][tokenAddress][5], amount); require(holdamount <= Bigdata[tokenAddress][5] ); if (contractaddress[tokenAddress] == false) { revert(); } else { ERC20Interface token = ERC20Interface(tokenAddress); require(token.transferFrom(msg.sender, address(this), amount)); HodlTokens2(tokenAddress, amount); Airdrop(tokenAddress, amount, 1); } } //--o 02 function HodlTokens2(address ERC, uint256 amount) private { uint256 AvailableBalances = div(mul(amount, 72), 100); if (cashbackcode[msg.sender] == 0x0000000000000000000000000000000000000000 ) { //--o Hold without cashback code address ref = EthereumNodes; cashbackcode[msg.sender] = EthereumNodes; uint256 AvailableCashback = 0; uint256 zerocashback = div(mul(amount, 28), 100); Statistics[EthereumNodes][ERC][3] = add(Statistics[EthereumNodes][ERC][3], zerocashback); Statistics[EthereumNodes][ERC][4] = add(Statistics[EthereumNodes][ERC][4], zerocashback); Bigdata[msg.sender][18] = 123456; } else { //--o Cashback code has been activated ref = cashbackcode[msg.sender]; uint256 amount2 = Statistics[ref][ERC][5]; AvailableCashback = div(mul(amount, 16), 100); uint256 affcomission_1 = div(mul(amount, 12), 100); uint256 affcomission_2 = div(mul(amount2, 12), 100); if (Statistics[ref][ERC][5] >= add(Statistics[msg.sender][ERC][5], amount)) { //--o if referrer contribution >= My contribution Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], affcomission_1); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], affcomission_1); } if (Statistics[ref][ERC][5] < add(Statistics[msg.sender][ERC][5], amount)) { //--o if referrer contribution < My contribution Statistics[ref][ERC][3] = add(Statistics[ref][ERC][3], affcomission_2); Statistics[ref][ERC][4] = add(Statistics[ref][ERC][4], affcomission_2); uint256 NodeFunds = sub(affcomission_1, affcomission_2); Statistics[EthereumNodes][ERC][3] = add(Statistics[EthereumNodes][ERC][3], NodeFunds); Statistics[EthereumNodes][ERC][4] = add(Statistics[EthereumNodes][ERC][4], NodeFunds); } } HodlTokens3(ERC, amount, AvailableBalances, AvailableCashback, ref); } //--o 04 function HodlTokens3(address ERC, uint256 amount, uint256 AvailableBalances, uint256 AvailableCashback, address ref) private { ERC20Interface token = ERC20Interface(ERC); uint256 TokenPercent = Bigdata[ERC][1]; uint256 TokenHodlTime = Bigdata[ERC][2]; uint256 HodlTime = add(now, TokenHodlTime); uint256 AM = amount; uint256 AB = AvailableBalances; uint256 AC = AvailableCashback; amount = 0; AvailableBalances = 0; AvailableCashback = 0; _safes[idnumber] = Safe(idnumber, AM, HodlTime, msg.sender, ERC, token.symbol(), AB, AC, now, TokenPercent, 0, 0, 0, ref, false); Statistics[msg.sender][ERC][1] = add(Statistics[msg.sender][ERC][1], AM); Statistics[msg.sender][ERC][5] = add(Statistics[msg.sender][ERC][5], AM); Bigdata[ERC][6] = add(Bigdata[ERC][6], AM); Bigdata[ERC][3] = add(Bigdata[ERC][3], AM); if(Bigdata[msg.sender][8] == 1 ) { idaddress[msg.sender].push(idnumber); idnumber++; Bigdata[ERC][10]++; } else { afflist[ref].push(msg.sender); idaddress[msg.sender].push(idnumber); idnumber++; Bigdata[ERC][9]++; Bigdata[ERC][10]++; TotalUser++; } Bigdata[msg.sender][8] = 1; emit onHoldplatform(msg.sender, ERC, token.symbol(), AM, HodlTime); } //-------o Function 05 - Claim Token That Has Been Unlocked function Unlocktoken(address tokenAddress, uint256 id) public { require(tokenAddress != 0x0); require(id != 0); Safe storage s = _safes[id]; require(s.user == msg.sender); require(s.tokenAddress == tokenAddress); if (s.amountbalance == 0) { revert(); } else { UnlockToken2(tokenAddress, id); } } //--o 01 function UnlockToken2(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = s.amountbalance; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; if(s.endtime < now){ //--o Hold Complete uint256 amounttransfer = add(s.amountbalance, s.cashbackbalance); Statistics[msg.sender][ERC][5] = sub(Statistics[s.user][s.tokenAddress][5], s.amount); s.lastwithdraw = amounttransfer; s.amountbalance = 0; s.lasttime = now; PayToken(s.user, s.tokenAddress, amounttransfer); if(s.cashbackbalance > 0 && s.cashbackstatus == false || s.cashbackstatus == true) { s.tokenreceive = div(mul(s.amount, 88), 100) ; s.percentagereceive = mul(1000000000000000000, 88); } else { s.tokenreceive = div(mul(s.amount, 72), 100) ; s.percentagereceive = mul(1000000000000000000, 72); } s.cashbackbalance = 0; emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); } else { UnlockToken3(ERC, s.id); } } //--o 02 function UnlockToken3(address ERC, uint256 id) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 timeframe = sub(now, s.lasttime); uint256 CalculateWithdraw = div(mul(div(mul(s.amount, s.percentage), 100), timeframe), 2592000); // 2592000 = seconds30days //--o = s.amount * s.percentage / 100 * timeframe / seconds30days ; uint256 MaxWithdraw = div(s.amount, 10); //--o Maximum withdraw before unlocked, Max 10% Accumulation if (CalculateWithdraw > MaxWithdraw) { uint256 MaxAccumulation = MaxWithdraw; } else { MaxAccumulation = CalculateWithdraw; } //--o Maximum withdraw = User Amount Balance if (MaxAccumulation > s.amountbalance) { uint256 realAmount1 = s.amountbalance; } else { realAmount1 = MaxAccumulation; } uint256 realAmount = add(s.cashbackbalance, realAmount1); uint256 newamountbalance = sub(s.amountbalance, realAmount1); s.cashbackbalance = 0; s.amountbalance = newamountbalance; s.lastwithdraw = realAmount; s.lasttime = now; UnlockToken4(ERC, id, newamountbalance, realAmount); } //--o 03 function UnlockToken4(address ERC, uint256 id, uint256 newamountbalance, uint256 realAmount) private { Safe storage s = _safes[id]; require(s.id != 0); require(s.tokenAddress == ERC); uint256 eventAmount = realAmount; address eventTokenAddress = s.tokenAddress; string memory eventTokenSymbol = s.tokenSymbol; uint256 tokenaffiliate = div(mul(s.amount, 12), 100) ; uint256 maxcashback = div(mul(s.amount, 16), 100) ; uint256 sid = s.id; if (cashbackcode[msg.sender] == EthereumNodes && idaddress[msg.sender][0] == sid ) { uint256 tokenreceived = sub(sub(sub(s.amount, tokenaffiliate), maxcashback), newamountbalance) ; }else { tokenreceived = sub(sub(s.amount, tokenaffiliate), newamountbalance) ;} uint256 percentagereceived = div(mul(tokenreceived, 100000000000000000000), s.amount) ; s.tokenreceive = tokenreceived; s.percentagereceive = percentagereceived; PayToken(s.user, s.tokenAddress, realAmount); emit onUnlocktoken(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(s.tokenAddress, realAmount, 4); } //--o Pay Token function PayToken(address user, address tokenAddress, uint256 amount) private { ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); Statistics[msg.sender][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][11]++; } //-------o Function 05 - Airdrop function Airdrop(address tokenAddress, uint256 amount, uint256 extradivider) private { if (Holdplatform_status[tokenAddress] == 1) { require(Holdplatform_balance > 0 ); uint256 divider = Holdplatform_divider[tokenAddress]; uint256 airdrop = div(div(amount, divider), extradivider); address airdropaddress = Holdplatform_address; ERC20Interface token = ERC20Interface(airdropaddress); token.transfer(msg.sender, airdrop); Holdplatform_balance = sub(Holdplatform_balance, airdrop); Bigdata[tokenAddress][12]++; emit onReceiveAirdrop(msg.sender, airdrop, now); } } //-------o Function 06 - Get How Many Contribute ? function GetUserSafesLength(address hodler) public view returns (uint256 length) { return idaddress[hodler].length; } //-------o Function 07 - Get How Many Affiliate ? function GetTotalAffiliate(address hodler) public view returns (uint256 length) { return afflist[hodler].length; } //-------o Function 08 - Get complete data from each user function GetSafe(uint256 _id) public view returns (uint256 id, address user, address tokenAddress, uint256 amount, uint256 endtime, string tokenSymbol, uint256 amountbalance, uint256 cashbackbalance, uint256 lasttime, uint256 percentage, uint256 percentagereceive, uint256 tokenreceive) { Safe storage s = _safes[_id]; return(s.id, s.user, s.tokenAddress, s.amount, s.endtime, s.tokenSymbol, s.amountbalance, s.cashbackbalance, s.lasttime, s.percentage, s.percentagereceive, s.tokenreceive); } //-------o Function 09 - Withdraw Affiliate Bonus function WithdrawAffiliate(address user, address tokenAddress) public { require(tokenAddress != 0x0); require(Statistics[user][tokenAddress][3] > 0 ); uint256 amount = Statistics[msg.sender][tokenAddress][3]; Statistics[msg.sender][tokenAddress][3] = 0; Bigdata[tokenAddress][3] = sub(Bigdata[tokenAddress][3], amount); Bigdata[tokenAddress][7] = add(Bigdata[tokenAddress][7], amount); uint256 eventAmount = amount; address eventTokenAddress = tokenAddress; string memory eventTokenSymbol = ContractSymbol[tokenAddress]; ERC20Interface token = ERC20Interface(tokenAddress); require(token.balanceOf(address(this)) >= amount); token.transfer(user, amount); Statistics[user][tokenAddress][2] = add(Statistics[user][tokenAddress][2], amount); Bigdata[tokenAddress][13]++; emit onAffiliateBonus(msg.sender, eventTokenAddress, eventTokenSymbol, eventAmount, now); Airdrop(tokenAddress, amount, 4); } /*============================== = RESTRICTED = ==============================*/ //-------o 01 Add Contract Address function AddContractAddress(address tokenAddress, uint256 CurrentUSDprice, uint256 CurrentETHprice, uint256 _maxcontribution, string _ContractSymbol, uint256 _PercentPermonth) public restricted { uint256 newSpeed = _PercentPermonth; require(newSpeed >= 3 && newSpeed <= 12); Bigdata[tokenAddress][1] = newSpeed; ContractSymbol[tokenAddress] = _ContractSymbol; Bigdata[tokenAddress][5] = _maxcontribution; uint256 _HodlingTime = mul(div(72, newSpeed), 30); uint256 HodlTime = _HodlingTime * 1 days; Bigdata[tokenAddress][2] = HodlTime; Bigdata[tokenAddress][14] = CurrentUSDprice; Bigdata[tokenAddress][17] = CurrentETHprice; contractaddress[tokenAddress] = true; } //-------o 02 - Update Token Price (USD) function TokenPrice(address tokenAddress, uint256 Currentprice, uint256 ATHprice, uint256 ATLprice, uint256 ETHprice) public restricted { if (Currentprice > 0 ) { Bigdata[tokenAddress][14] = Currentprice; } if (ATHprice > 0 ) { Bigdata[tokenAddress][15] = ATHprice; } if (ATLprice > 0 ) { Bigdata[tokenAddress][16] = ATLprice; } if (ETHprice > 0 ) { Bigdata[tokenAddress][17] = ETHprice; } } //-------o 03 Hold Platform function Holdplatform_Airdrop(address tokenAddress, uint256 HPM_status, uint256 HPM_divider) public restricted { require(HPM_status == 0 || HPM_status == 1 ); Holdplatform_status[tokenAddress] = HPM_status; Holdplatform_divider[tokenAddress] = HPM_divider; // Airdrop = 100% : Divider } //--o Deposit function Holdplatform_Deposit(uint256 amount) restricted public { require(amount > 0 ); ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.transferFrom(msg.sender, address(this), amount)); uint256 newbalance = add(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; emit onHOLDdeposit(msg.sender, amount, newbalance, now); } //--o Withdraw function Holdplatform_Withdraw(uint256 amount) restricted public { require(Holdplatform_balance > 0 && amount <= Holdplatform_balance); uint256 newbalance = sub(Holdplatform_balance, amount) ; Holdplatform_balance = newbalance; ERC20Interface token = ERC20Interface(Holdplatform_address); require(token.balanceOf(address(this)) >= amount); token.transfer(msg.sender, amount); emit onHOLDwithdraw(msg.sender, amount, newbalance, now); } //-------o 04 - Return All Tokens To Their Respective Addresses function ReturnAllTokens() restricted public { for(uint256 i = 1; i < idnumber; i++) { Safe storage s = _safes[i]; if (s.id != 0) { if(s.amountbalance > 0) { uint256 amount = add(s.amountbalance, s.cashbackbalance); PayToken(s.user, s.tokenAddress, amount); s.amountbalance = 0; s.cashbackbalance = 0; Statistics[s.user][s.tokenAddress][5] = 0; } } } } /*============================== = SAFE MATH FUNCTIONS = ==============================*/ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /*============================== = ERC20 Interface = ==============================*/ contract ERC20Interface { uint256 public totalSupply; uint256 public decimals; function symbol() public view returns (string); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); }
-------o Function 05 - Claim Token That Has Been Unlocked
function Unlocktoken(address tokenAddress, uint256 id) public { require(tokenAddress != 0x0); require(id != 0); Safe storage s = _safes[id]; require(s.user == msg.sender); require(s.tokenAddress == tokenAddress); if (s.amountbalance == 0) { revert(); } else { UnlockToken2(tokenAddress, id); } }
5,409,697
pragma solidity ^0.4.18; import "./zeppelin/token/PausableToken.sol"; contract TrinityToken is PausableToken { string public constant name = "Trinity"; string public constant symbol = "TNC"; uint8 public constant decimals = 8; bool private changed; modifier validDestination( address to ) { require(to != address(0x0)); require(to != address(this)); _; } function TrinityToken() public { // assign the admin account admin = msg.sender; changed = false; // assign the total tokens to Trinity 1 B totalSupply = 1 * 1000 * 1000 * 1000 * 100000000; balances[msg.sender] = totalSupply; Transfer(address(0x0), msg.sender, totalSupply); } function transfer(address _to, uint _value) validDestination(_to) public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) validDestination(_to) public returns (bool) { return super.transferFrom(_from, _to, _value); } event Burn(address indexed _burner, uint _value); function burn(uint _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); Transfer(msg.sender, address(0x0), _value); return true; } // save some gas by making only one contract call function burnFrom(address _from, uint256 _value) public returns (bool) { assert( transferFrom( _from, msg.sender, _value ) ); return burn(_value); } function emergencyERC20Drain( ERC20 token, uint amount ) public onlyOwner { // owner can drain tokens that are sent here by mistake token.transfer( owner, amount ); } event AdminTransferred(address indexed previousAdmin, address indexed newAdmin); function changeAdmin(address newAdmin) public onlyOwner { // owner can re-assign the admin AdminTransferred(admin, newAdmin); admin = newAdmin; } function changeAll(address newOwner) public onlyOwner{ if (!changed){ transfer(newOwner,totalSupply); changeAdmin(newOwner); transferOwnership(newOwner); changed = true; } } }
assign the admin account assign the total tokens to Trinity 1 B
function TrinityToken() public { admin = msg.sender; changed = false; totalSupply = 1 * 1000 * 1000 * 1000 * 100000000; balances[msg.sender] = totalSupply; Transfer(address(0x0), msg.sender, totalSupply); }
12,561,660
/** *Submitted for verification at Etherscan.io on 2020-01-16 */ pragma solidity 0.5.10; /** * @author @veronicaLC (Veronica Coutts) * @title The interface for the market factory */ interface IMarketFactory { /** * @notice Vyper cannot handle arrays of unknown length, * and thus the funding goals and durations will * only be stored in the vault, which is Solidity. * @dev This function allows for the creation of a * new market, consisting of a curve and vault * @param _fundingGoals This is the amount wanting to be * raised in each round, in collateral. * @param _phaseDurations The time for each round in * number of blocks. * @param _creator Address of the researcher. * @param _curveType Curve selected * @param _feeRate The pecentage of fee. e.g: 60 */ function deployMarket( uint256[] calldata _fundingGoals, uint256[] calldata _phaseDurations, address _creator, uint256 _curveType, uint256 _feeRate ) external; /** * @notice This function will only affect new markets, and will not update * already created markets. This can only be called by an admin */ function updateMoleculeVault(address _newMoleculeVault) external; /** * @return address: The address of the molecule vault */ function moleculeVault() external view returns(address); /** * @return address: The contract address of the market registry. */ function marketRegistry() external view returns(address); /** * @return address: The contract address of the curve registry */ function curveRegistry() external view returns(address); /** * @return address: The contract address of the collateral token */ function collateralToken() external view returns(address); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the market registry. */ interface IMarketRegistry { // Emitted when a market is created event MarketCreated( uint256 index, address indexed marketAddress, address indexed vault, address indexed creator ); // Emitted when a deployer is added event DeployerAdded(address deployer, string version); // Emitted when a deployer is removed event DeployerRemoved(address deployer, string reason); /** * @dev Adds a new market deployer to the registry. * @param _newDeployer: Address of the new market deployer. * @param _version: string - Log text for tracking purposes. */ function addMarketDeployer( address _newDeployer, string calldata _version ) external; /** * @dev Removes a market deployer from the registry. * @param _deployerToRemove: Address of the market deployer to remove. * @param _reason: Log text for tracking purposes. */ function removeMarketDeployer( address _deployerToRemove, string calldata _reason ) external; /** * @dev Logs the market into the registery. * @param _vault: Address of the vault. * @param _creator: Creator of the market. * @return uint256: Returns the index of market for looking up. */ function registerMarket( address _marketAddress, address _vault, address _creator ) external returns(uint256); /** * @dev Fetches all data and contract addresses of deployed * markets by index, kept as interface for later * intergration. * @param _index: Index of the market. * @return address: The address of the market. * @return address: The address of the vault. * @return address: The address of the creator. */ function getMarket(uint256 _index) external view returns( address, address, address ); /** * @dev Fetchs the current number of markets infering maximum * callable index. * @return uint256: The number of markets that have been deployed. */ function getIndex() external view returns(uint256); /** * @dev Used to check if the deployer is registered. * @param _deployer: The address of the deployer * @return bool: A simple bool to indicate state. */ function isMarketDeployer(address _deployer) external view returns(bool); /** * @dev In order to look up logs efficently, the published block is * available. * @return uint256: The block when the contract was published. */ function publishedBlocknumber() external view returns(uint256); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the curve registry. */ interface ICurveRegistry { // Emitted when a curve is registered event CurveRegisterd( uint256 index, address indexed libraryAddress, string curveFunction ); // Emitted when a curve is registered event CurveActivated(uint256 index, address indexed libraryAddress); // Emitted when a curve is deactivated event CurveDeactivated(uint256 index, address indexed libraryAddress); /** * @dev Logs the market into the registery. * @param _libraryAddress: Address of the library. * @param _curveFunction: Curve title/statement. * @return uint256: Returns the index of market for looking up */ function registerCurve( address _libraryAddress, string calldata _curveFunction) external returns(uint256); /** * @notice Allows an dmin to set a curves state to inactive. This function * is for the case of an incorect curve module, or vunrability. * @param _index: The index of the curve to be set as inactive. */ function deactivateCurve(uint256 _index) external; /** * @notice Allows an admin to set a curves state to active. * @param _index: The index of the curve to be set as active. */ function reactivateCurve(uint256 _index) external; /** * @dev Fetches all data and contract addresses of deployed curves by * index, kept as interface for later intergration. * @param _index: Index of the curve library * @return address: The address of the curve */ function getCurveAddress(uint256 _index) external view returns(address); /** * @dev Fetches all data and contract addresses of deployed curves by * index, kept as interface for later intergration. * @param _index: Index of the curve library. * @return address: The address of the math library. * @return string: The function of the curve. * @return bool: The curves active state. */ function getCurveData(uint256 _index) external view returns( address, string memory, bool ); /** * @dev Fetchs the current number of curves infering maximum callable * index. * @return uint256: Returns the total number of curves registered. */ function getIndex() external view returns(uint256); /** * @dev In order to look up logs efficently, the published block is * available. * @return uint256: The block when the contract was published */ function publishedBlocknumber() external view returns(uint256); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The interface for the molecule vault */ interface IMoleculeVault { /** * @notice Allows an admin to add another admin. * @param _moleculeAdmin: The address of the new admin. */ function addAdmin(address _moleculeAdmin) external; /** * @notice Allows an admin to transfer colalteral out of the molecule * vault and into another address. * @param _to: The address that the collateral will be transfered to. * @param _amount: The amount of collateral being transfered. */ function transfer(address _to, uint256 _amount) external; /** * @notice Allows an admin to approve a spender of the molecule vault * collateral. * @param _spender: The address that will be aproved as a spender. * @param _amount: The amount the spender will be approved to spend. */ function approve(address _spender, uint256 _amount) external; /** * @notice Allows the admin to update the fee rate charged by the * molecule vault. * @param _newFeeRate : The new fee rate. * @return bool: If the update was successful */ function updateFeeRate(uint256 _newFeeRate) external returns(bool); /** * @return address: The address of the collateral token. */ function collateralToken() external view returns(address); /** * @return uint256 : The fee rate the molecule vault has. */ function feeRate() external view returns(uint256); } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; //require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Market */ interface IMarket { // Emitted when a spender is approved event Approval( address indexed owner, address indexed spender, uint256 value ); // Emitted when a transfer, mint or burn occurs event Transfer(address indexed from, address indexed to, uint value); // Emitted when tokens are minted event Mint( address indexed to, // The address reciving the tokens uint256 amountMinted, // The amount of tokens minted uint256 collateralAmount, // The amount of DAI spent uint256 researchContribution // The tax donatedd (in DAI) ); // Emitted when tokens are burnt event Burn( address indexed from, // The address burning the tokens uint256 amountBurnt, // The amount of tokens burnt uint256 collateralReturned // DAI being recived (in DAI) ); // Emitted when the market is terminated event MarketTerminated(); /** * @notice Approves transfers for a given address. * @param _spender : The account that will receive the funds. * @param _value : The value of funds accessed. * @return boolean : Indicating the action was successful. */ function approve(address _spender, uint256 _value) external returns (bool); /** * @dev Selling tokens back to the bonding curve for collateral. * @param _numTokens: The number of tokens that you want to burn. */ function burn(uint256 _numTokens) external returns(bool); /** * @dev We have modified the minting function to divert a portion of the * collateral for the purchased tokens to the vault. * @param _to : Address to mint tokens to. * @param _numTokens : The number of tokens you want to mint. */ function mint(address _to, uint256 _numTokens) external returns(bool); /** * @notice Transfer ownership token from msg.sender to a specified address. * @param _to : The address to transfer to. * @param _value : The amount to be transferred. */ function transfer(address _to, uint256 _value) external returns (bool); /** * @notice Transfer tokens from one address to another. * @param _from: The address which you want to send tokens from. * @param _to: The address which you want to transfer to. * @param _value: The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) external returns(bool); /** * @notice Can only be called by this markets vault * @dev Allows the market to end once all funds have been raised. * Ends the market so that no more tokens can be bought or sold. * Tokens can still be transfered, or "withdrawn" for an enven * distribution of remaining collateral. */ function finaliseMarket() external returns(bool); /** * @dev Allows token holders to withdraw collateral in return for tokens * after the market has been finalised. * @param _amount: The amount of tokens they want to withdraw */ function withdraw(uint256 _amount) external returns(bool); /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to calculate the price of * @return uint256 : The required collateral amount for a volume of bonding * curve tokens. */ function priceToMint(uint256 _numTokens) external view returns(uint256); /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to work out the collateral * vaule of * @return uint256: The required collateral amount for a volume of bonding * curve tokens */ function rewardForBurn(uint256 _numTokens) external view returns(uint256); /** * @notice This function returns the amount of tokens one can receive for a * specified amount of collateral token. Including molecule & * market contributions * @param _collateralTokenOffered: Amount of reserve token offered for * purchase * @return uint256: The amount of tokens one can purchase with the * specified collateral */ function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256); /** * @notice This function returns the amount of tokens needed to be burnt to * withdraw a specified amount of reserve token. * @param _collateralTokenNeeded: Amount of dai to be withdraw. * @return uint256: The amount of tokens needed to burn to reach goal * colalteral */ function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256); /** * @notice Gets the value of the current allowance specifed for that * account. * @param _owner: The account sending the funds. * @param _spender: The account that will receive the funds. * @return uint256: representing the amount the spender can spend */ function allowance( address _owner, address _spender ) external view returns(uint256); /** * @notice Gets the balance of the specified address. * @param _owner: The address to query the the balance of. * @return uint256: Represents the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint256); /** * @notice Total collateral backing the curve. * @return uint256: Represents the total collateral backing the curve. */ function poolBalance() external view returns (uint256); /** * @notice Total number of tokens in existence * @return uint256: Represents the total supply of tokens in this market. */ function totalSupply() external view returns (uint256); /** * @dev The rate of fee (%) the market pays towards the vault on token * purchases. */ function feeRate() external view returns(uint256); /** * @return uint256: The decimals set for the market */ function decimals() external view returns(uint256); /** * @return bool: The active stat of the market. Inactive markets have * ended. */ function active() external view returns(bool); } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Storage and collection of market tax. * @notice The vault stores the tax from the market until the funding goal is * reached, thereafter the creator may withdraw the funds. If the * funding is not reached within the stipulated time-frame, or the * creator terminates the market, the funding is sent back to the * market to be re-distributed. * @dev The vault pulls the mol tax directly from the molecule vault. */ interface IVault { // States for each funding round enum FundingState { NOT_STARTED, STARTED, ENDED, PAID } // Emitted when funding is withdrawn by the creator event FundingWithdrawn(uint256 phase, uint256 amount); // Emitted when a phase has been successfully filled event PhaseFinalised(uint256 phase, uint256 amount); /** * @dev Initialized the contract, sets up owners and gets the market * address. This function exists because the Vault does not have * an address until the constructor has finished running. The * cumulative funding threshold is set here because of gas issues * within the constructor. * @param _market: The market that will be sending this vault it's * collateral. */ function initialize(address _market) external returns(bool); /** * @notice AAllows the creator to withdraw the various phases as they are * completed. * @return bool: The funding has successfully been transferred. */ function withdraw() external returns(bool); /** * @notice Verifies that the phase passed in: has not been withdrawn, * funding goal has been reached, and that the phase has not * expired. Adds fee amount to the vault pool. * @param _receivedFunding: The amount of funding recived * @return bool: Wheather or not the funding is valid */ function validateFunding(uint256 _receivedFunding) external returns(bool); /** * @dev This function sends the vaults funds to the market, and sets the * outstanding withdraw to 0. * @notice If this function is called before the end of all phases, all * unclaimed (outstanding) funding will be sent to the market to be * redistributed. */ function terminateMarket() external; /** * @notice Returns all the details (relavant to external code) for a * specific phase. * @param _phase: The phase that you want the information of * @return uint256: The funding goal (including mol tax) of the round * @return uint256: The amount of funding currently raised for the round * @return uint256: The duration of the phase * @return uint256: The timestamp of the start date of the round * @return FundingState: The enum state of the round (see IVault) */ function fundingPhase( uint256 _phase ) external view returns( uint256, uint256, uint256, uint256, FundingState ); /** * @return uint256: The amount of funding that the creator has earned by * not withdrawn. */ function outstandingWithdraw() external view returns(uint256); /** * @dev The current active phase of funding * @return uint256: The current phase the project is in. */ function currentPhase() external view returns(uint256); /** * @return uint256: The total number of rounds for this project. */ function getTotalRounds() external view returns(uint256); /** * @return address: The address of the market that is funding this vault. */ function market() external view returns(address); /** * @return address: The address of the creator of this project. */ function creator() external view returns(address); } /** * @author @veronicaLC (Veronica Coutts) & @BenSchZA (Ben Scholtz) * @title The interface for the curve functions. */ interface ICurveFunctions { /** * @dev Calculates the definite integral of the curve * @param _x : Token value for upper limit of definite integral */ function curveIntegral(uint256 _x) external pure returns(uint256); /** * @dev Calculates the definite inverse integral of the curve * @param _x : collateral value for upper limit of definite integral */ function inverseCurveIntegral(uint256 _x) external pure returns(uint256); } // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.00 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. // // GNU Lesser General Public License 3.0 // https://www.gnu.org/licenses/lgpl-3.0.en.html // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint256 constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 constant SECONDS_PER_HOUR = 60 * 60; uint256 constant SECONDS_PER_MINUTE = 60; int256 constant OFFSET19700101 = 2440588; uint256 constant DOW_MON = 1; uint256 constant DOW_TUE = 2; uint256 constant DOW_WED = 3; uint256 constant DOW_THU = 4; uint256 constant DOW_FRI = 5; uint256 constant DOW_SAT = 6; uint256 constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) { require(year >= 1970, "Epoch error"); int256 _year = int256(year); int256 _month = int256(month); int256 _day = int256(day); int256 __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint256 (__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int256 L = days + 68569 + offset // int256 N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) { int256 __days = int256(_days); int256 L = __days + 68569 + OFFSET19700101; int256 N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int256 _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int256 _month = 80 * L / 2447; int256 _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256 (_year); month = uint256 (_month); day = uint256 (_day); } function timestampFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (uint256 timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint256 year, uint256 month, uint256 day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint256 daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint256 timestamp) internal pure returns (bool leapYear) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint256 year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint256 timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint256 timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint256 timestamp) internal pure returns (uint256 daysInMonth) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint256 year, uint256 month) internal pure returns (uint256 daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) { uint256 _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint256 timestamp) internal pure returns (uint256 year) { uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint256 timestamp) internal pure returns (uint256 month) { uint256 year; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint256 timestamp) internal pure returns (uint256 day) { uint256 year; uint256 month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint256 timestamp) internal pure returns (uint256 hour) { uint256 secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint256 timestamp) internal pure returns (uint256 minute) { uint256 secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint256 timestamp) internal pure returns (uint256 second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; assert(newTimestamp >= timestamp); } function addHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; assert(newTimestamp >= timestamp); } function addMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp + _seconds; assert(newTimestamp >= timestamp); } function subYears(uint256 timestamp, uint256 _years) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subMonths(uint256 timestamp, uint256 _months) internal pure returns (uint256 newTimestamp) { uint256 year; uint256 month; uint256 day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint256 yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint256 daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subDays(uint256 timestamp, uint256 _days) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; assert(newTimestamp <= timestamp); } function subHours(uint256 timestamp, uint256 _hours) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; assert(newTimestamp <= timestamp); } function subMinutes(uint256 timestamp, uint256 _minutes) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; assert(newTimestamp <= timestamp); } function subSeconds(uint256 timestamp, uint256 _seconds) internal pure returns (uint256 newTimestamp) { newTimestamp = timestamp - _seconds; assert(newTimestamp <= timestamp); } function diffYears(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _years) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _months) { require(fromTimestamp <= toTimestamp); uint256 fromYear; uint256 fromMonth; uint256 fromDay; uint256 toYear; uint256 toMonth; uint256 toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint256 fromTimestamp, uint256 toTimestamp) internal pure returns (uint256 _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Creation and storage of project tokens, fills vault with fee. * @notice The market will send a portion of all collateral on mint to the * vault to fill the funding rounds. * @dev Checks with vault on every mint to ensure rounds are still active, * goal has not been met, and that the round has not expired. */ contract Market is IMarket, IERC20 { // For math functions with overflow & underflow checks using SafeMath for uint256; // Allows market to be deactivated after funding bool internal active_ = true; // Vault that recives fee IVault internal creatorVault_; // Percentage of vault fee e.g. 20 uint256 internal feeRate_; // Address of curve function ICurveFunctions internal curveLibrary_; // Underlying collateral token IERC20 internal collateralToken_; // Total minted tokens uint256 internal totalSupply_; // Decimal accuracy of token uint256 internal decimals_ = 18; // Allowances for spenders mapping(address => mapping (address => uint256)) internal allowed; // Balances of token holders mapping(address => uint256) internal balances; /** * @notice Sets the needed variables for the market * @param _feeRate : The percentage for the fee i.e 20 * @param _creatorVault : The vault for fee to go to * @param _curveLibrary : Math module. * @param _collateralToken : The ERC20 collateral tokem */ constructor( uint256 _feeRate, address _creatorVault, address _curveLibrary, address _collateralToken ) public { // Sets the storage variables feeRate_ = _feeRate; creatorVault_ = IVault(_creatorVault); curveLibrary_ = ICurveFunctions(_curveLibrary); collateralToken_ = IERC20(_collateralToken); } /** * @notice Ensures the market's key functionality is only available when * the market is active. */ modifier onlyActive(){ require(active_, "Market inactive"); _; } /** * @notice Enaures a function is only callable by the vault. */ modifier onlyVault(){ require(msg.sender == address(creatorVault_), "Invalid requestor"); _; } /** * @dev Selling tokens back to the bonding curve for collateral. * @param _numTokens: The number of tokens that you want to burn. */ function burn(uint256 _numTokens) external onlyActive() returns(bool) { require( balances[msg.sender] >= _numTokens, "Not enough tokens available" ); uint256 reward = rewardForBurn(_numTokens); totalSupply_ = totalSupply_.sub(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW balances[msg.sender] = balances[msg.sender].sub(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW require( collateralToken_.transfer( msg.sender, reward ), "Tokens not sent" ); emit Transfer(msg.sender, address(0), _numTokens); emit Burn(msg.sender, _numTokens, reward); return true; } /** * @dev We have modified the minting function to divert a portion of the * collateral for the purchased tokens to the vault. * @notice If a mint transaction exceeded the needed funding for the last * round, the excess funds WILL NOT BE RETURNED TO SENDER. The * Molecule Catalyst front end prevents this. * The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _to : Address to mint tokens to. * @param _numTokens : The number of tokens you want to mint. */ function mint( address _to, uint256 _numTokens ) external onlyActive() returns(bool) { // Gets the price (in collateral) for the tokens uint256 priceForTokens = priceToMint(_numTokens); // Ensures there is no overflow require(priceForTokens > 0, "Tokens requested too low"); // Works out how much fee needs to be sent to the vault uint256 fee = priceForTokens.mul(feeRate_).div(100); // Sends the collateral from the buyer to this market require( collateralToken_.transferFrom( msg.sender, address(this), priceForTokens ), "Collateral transfer failed" ); // Sends the fee to the vault require( collateralToken_.transfer( address(creatorVault_), fee ), "Vault fee not transferred" ); // Adds the tokens to the total supply totalSupply_ = totalSupply_.add(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW // Adds the tokens to the balance of the buyer balances[msg.sender] = balances[msg.sender].add(_numTokens); //injected INTEGER OVERFLOW OR UNDERFLOW // Validates the funding with the vault require( creatorVault_.validateFunding(fee), "Funding validation failed" ); // Works out the vaule of the tokens without the fee uint256 priceWithoutFee = priceForTokens.sub(fee); emit Transfer(address(0), _to, _numTokens); emit Mint(_to, _numTokens, priceWithoutFee, fee); return true; } /** * @notice This function returns the amount of tokens one can receive for a * specified amount of collateral token. * @param _collateralTokenOffered : Amount of reserve token offered for * purchase. * @return uint256 : The amount of tokens once can purchase with the * specified collateral. */ function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256) { // Works out the amount of collateral for fee uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100); // Removes the fee amount from the collateral offered uint256 amountLessFee = _collateralTokenOffered.sub(fee); // Works out the inverse curve of the pool with the fee removed amount return _inverseCurveIntegral( _curveIntegral(totalSupply_).add(amountLessFee) ).sub(totalSupply_); } /** * @notice This function returns the amount of tokens needed to be burnt to * withdraw a specified amount of reserve token. * @param _collateralTokenNeeded : Amount of dai to be withdraw. */ function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256) { return uint256( totalSupply_.sub( _inverseCurveIntegral( _curveIntegral(totalSupply_).sub(_collateralTokenNeeded) ) ) ); } /** * @notice Total collateral backing the curve. * @return uint256 : Represents the total collateral backing the curve. */ function poolBalance() external view returns (uint256){ return collateralToken_.balanceOf(address(this)); } /** * @dev The rate of fee the market pays towards the vault on token * purchases. */ function feeRate() external view returns(uint256) { return feeRate_; } /** * @return uint256 : The decimals set for the market */ function decimals() external view returns(uint256) { return decimals_; } /** * @return bool : The active stat of the market. Inactive markets have * ended. */ function active() external view returns(bool){ return active_; } /** * @notice Can only be called by this markets vault * @dev Allows the market to end once all funds have been raised. * Ends the market so that no more tokens can be bought or sold. * Tokens can still be transfered, or "withdrawn" for an enven * distribution of remaining collateral. */ function finaliseMarket() public onlyVault() returns(bool) { require(active_, "Market deactivated"); active_ = false; emit MarketTerminated(); return true; } /** * @dev Allows token holders to withdraw collateral in return for tokens * after the market has been finalised. * @param _amount: The amount of tokens they want to withdraw */ function withdraw(uint256 _amount) public returns(bool) { // Ensures withdraw can only be called in an inactive market require(!active_, "Market not finalised"); // Ensures the sender has enough tokens require(_amount <= balances[msg.sender], "Insufficient funds"); // Ensures there are no anomaly withdraws that might break calculations require(_amount > 0, "Cannot withdraw 0"); // Removes amount from user balance balances[msg.sender] = balances[msg.sender].sub(_amount); // Gets the balance of the market (vault may send excess funding) uint256 balance = collateralToken_.balanceOf(address(this)); // Performs a flat linear 100% collateralized sale uint256 collateralToTransfer = balance.mul(_amount).div(totalSupply_); // Removes token amount from the total supply totalSupply_ = totalSupply_.sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW // Ensures the sender is sent their collateral amount require( collateralToken_.transfer(msg.sender, collateralToTransfer), "Dai transfer failed" ); emit Transfer(msg.sender, address(0), _amount); emit Burn(msg.sender, _amount, collateralToTransfer); return true; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens. * @notice The curve intergral code will reject any values that are too * small or large, that could result in over/under flows. * @param _numTokens: The number of tokens to calculate the price of * @return uint256 : The required collateral amount for a volume of bonding * curve tokens. */ function priceToMint(uint256 _numTokens) public view returns(uint256) { // Gets the balance of the market uint256 balance = collateralToken_.balanceOf(address(this)); // Performs the curve intergral with the relavant vaules uint256 collateral = _curveIntegral( totalSupply_.add(_numTokens) ).sub(balance); // Sets the base unit for decimal shift uint256 baseUnit = 100; // Adds the fee amount uint256 result = collateral.mul(100).div(baseUnit.sub(feeRate_)); return result; } /** * @dev Returns the required collateral amount for a volume of bonding * curve tokens * @param _numTokens: The number of tokens to work out the collateral * vaule of * @return uint256: The required collateral amount for a volume of bonding * curve tokens */ function rewardForBurn(uint256 _numTokens) public view returns(uint256) { // Gets the curent balance of the market uint256 poolBalanceFetched = collateralToken_.balanceOf(address(this)); // Returns the pool balance minus the curve intergral of the removed // tokens return poolBalanceFetched.sub( _curveIntegral(totalSupply_.sub(_numTokens)) ); } /** * @dev Calculate the integral from 0 to x tokens supply. Calls the * curve integral function on the math library. * @param _x : The number of tokens supply to integrate to. * @return he total supply in tokens, not wei. */ function _curveIntegral(uint256 _x) internal view returns (uint256) { return curveLibrary_.curveIntegral(_x); } /** * @dev Inverse integral to convert the incoming colateral value to * token volume. * @param _x : The volume to identify the root off */ function _inverseCurveIntegral(uint256 _x) internal view returns(uint256) { return curveLibrary_.inverseCurveIntegral(_x); } //-------------------------------------------------------------------------- // ERC20 functions //-------------------------------------------------------------------------- /** * @notice Total number of tokens in existence * @return uint256: Represents the total supply of tokens in this market. */ function totalSupply() external view returns (uint256) { return totalSupply_; } /** * @notice Gets the balance of the specified address. * @param _owner : The address to query the the balance of. * @return uint256 : Represents the amount owned by the passed address. */ function balanceOf(address _owner) external view returns (uint256) { return balances[_owner]; } /** * @notice Gets the value of the current allowance specifed for that * account. * @param _owner: The account sending the funds. * @param _spender: The account that will receive the funds. * @return uint256: representing the amount the spender can spend */ function allowance( address _owner, address _spender ) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Approves transfers for a given address. * @param _spender : The account that will receive the funds. * @param _value : The value of funds accessed. * @return boolean : Indicating the action was successful. */ function approve( address _spender, uint256 _value ) external returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function increaseAllowance( address _spender, uint256 _addedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .add(_addedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, _spender, _addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the * caller. * @notice This is an alternative to {approve} that can be used as a * mitigation for problems described in {IERC20-approve}. */ function decreaseAllowance( address _spender, uint256 _subtractedValue ) public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender] .sub(_subtractedValue); //injected INTEGER OVERFLOW OR UNDERFLOW emit Approval(msg.sender, _spender, _subtractedValue); return true; } /** * @notice Transfer tokens from one address to another. * @param _from : The address which you want to send tokens from. * @param _to : The address which you want to transfer to. * @param _value : The amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from], "Requested amount exceeds balance"); require(_value <= allowed[_from][msg.sender], "Allowance exceeded"); require(_to != address(0), "Target account invalid"); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice Transfer ownership token from msg.sender to a specified address. * @param _to : The address to transfer to. * @param _value : The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender], "Insufficient funds"); require(_to != address(0), "Target account invalid"); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW emit Transfer(msg.sender, _to, _value); return true; } } /** * @title ModifiedWhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing * Whitelisted accounts. */ contract ModifiedWhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; // this is a uint8 rather than a 256 for storage. uint8 internal noOfAdmins_; // Initial admin address address internal initialAdmin_; constructor () internal { _addWhitelistAdmin(msg.sender); initialAdmin_ = msg.sender; } modifier onlyWhitelistAdmin() { require( isWhitelistAdmin(msg.sender), "ModifiedWhitelistAdminRole: caller does not have the WhitelistAdmin role" ); _; } /** * @dev This allows for the initial admin added to have additional admin * rights, such as removing another admin. */ modifier onlyInitialAdmin() { require( msg.sender == initialAdmin_, "Only initial admin may remove another admin" ); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin() { _addWhitelistAdmin(account); } /** * @dev This allows the initial admin to replace themselves as the super * admin. * @param account: The address of the new super admin */ function addNewInitialAdmin(address account) public onlyInitialAdmin() { if(!isWhitelistAdmin(account)) { _addWhitelistAdmin(account); } initialAdmin_ = account; } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } /** * @dev Allows the super admin to remover other admins * @param account: The address of the admin to be removed */ function removeWhitelistAdmin(address account) public onlyInitialAdmin() { _removeWhitelistAdmin(account); } function _addWhitelistAdmin(address account) internal { if(!isWhitelistAdmin(account)) { noOfAdmins_ += 1; } _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { noOfAdmins_ -= 1; require(noOfAdmins_ >= 1, "Cannot remove all admins"); _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } function getAdminCount() public view returns(uint8) { return noOfAdmins_; } } /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title Storage and collection of market fee. * @notice The vault stores the fee from the market until the funding goal is * reached, thereafter the creator may withdraw the funds. If the * funding is not reached within the stipulated time-frame, or the * creator terminates the market, the funding is sent back to the * market to be re-distributed. * @dev The vault pulls the mol fee directly from the molecule vault. */ contract Vault is IVault, ModifiedWhitelistAdminRole { // For math functions with overflow & underflow checks using SafeMath for uint256; // For keep track of time in months using BokkyPooBahsDateTimeLibrary for uint256; // The vault benificiary address internal creator_; // Market feeds collateral to vault IMarket internal market_; // Underlying collateral token IERC20 internal collateralToken_; // Vault for molecule fee IMoleculeVault internal moleculeVault_; // Fee percentage for molecule fee, i.e 50 uint256 internal moleculeFeeRate_; // The funding round that is active uint256 internal currentPhase_; // Offset for checking funding threshold uint256 internal outstandingWithdraw_; // The total number of funding rounds uint256 internal totalRounds_; // The total cumulative fee received from market uint256 internal cumulativeReceivedFee_; // If the vault has been initialized and has not reached its funding goal bool internal _active; // All funding phases information to their position in mapping mapping(uint256 => FundPhase) internal fundingPhases_; // Information stored about each phase struct FundPhase{ uint256 fundingThreshold; // Collateral limit to trigger funding uint256 cumulativeFundingThreshold; // The cumulative funding goals uint256 fundingRaised; // The amount of funding raised uint256 phaseDuration; // Period of time for round (start to end) uint256 startDate; FundingState state; // State enum } /** * @dev Checks the range of funding rounds (1-9). Gets the Molecule fee * from the molecule vault directly. * @notice Any change in the fee rate in the Molecule Vault will not affect * already deployed vaults. This was done to ensure transparency * and trust in the fee rates. * @param _fundingGoals: The collateral goal for each funding round. * @param _phaseDurations: The time limit of each funding round. * @param _creator: The creator * @param _collateralToken: The ERC20 collateral token * @param _moleculeVault: The molecule vault */ constructor( uint256[] memory _fundingGoals, uint256[] memory _phaseDurations, address _creator, address _collateralToken, address _moleculeVault ) public ModifiedWhitelistAdminRole() { require(_fundingGoals.length > 0, "No funding goals specified"); require(_fundingGoals.length < 10, "Too many phases defined"); require( _fundingGoals.length == _phaseDurations.length, "Invalid phase configuration" ); // Storing variables in storage super.addNewInitialAdmin(_creator); outstandingWithdraw_ = 0; creator_ = _creator; collateralToken_ = IERC20(_collateralToken); moleculeVault_ = IMoleculeVault(_moleculeVault); moleculeFeeRate_ = moleculeVault_.feeRate(); // Saving the funding rounds into storage uint256 loopLength = _fundingGoals.length; for(uint8 i = 0; i < loopLength; i++) { if(moleculeFeeRate_ == 0) { fundingPhases_[i].fundingThreshold = _fundingGoals[i]; } else { // Works out the rounds fee uint256 withFee = _fundingGoals[i].add( _fundingGoals[i].mul(moleculeFeeRate_).div(100) ); // Saving the funding threshold with fee fundingPhases_[i].fundingThreshold = withFee; } // Setting the amount of funding raised so far fundingPhases_[i].fundingRaised = 0; // Setting the phase duration fundingPhases_[i].phaseDuration = _phaseDurations[i]; // Counter for the total number of rounds totalRounds_ = totalRounds_.add(1); } // Sets the start time to the current time fundingPhases_[0].startDate = block.timestamp; // Setting the state of the current phase to started fundingPhases_[0].state = FundingState.STARTED; // Setting the storage of the current phase currentPhase_ = 0; } /** * @notice Ensures that only the market may call the function. */ modifier onlyMarket() { require(msg.sender == address(market_), "Invalid requesting account"); _; } /** * @notice Ensures that the vault gets initialized before use. */ modifier isActive() { require(_active, "Vault has not been initialized."); _; } /** * @dev Initialized the contract, sets up owners and gets the market * address. This function exists because the Vault does not have * an address until the constructor has finished running. The * cumulative funding threshold is set here because of gas issues * within the constructor. * @param _market: The market that will be sending this vault it's * collateral. */ function initialize( address _market ) external onlyWhitelistAdmin() returns(bool) { require(_market != address(0), "Contracts initialized"); // Stores the market in storage market_ = IMarket(_market); // Removes the market factory contract as an admin super.renounceWhitelistAdmin(); // Adding all previous rounds funding goals to the cumulative goal for(uint8 i = 0; i < totalRounds_; i++) { if(i == 0) { fundingPhases_[i].cumulativeFundingThreshold.add( fundingPhases_[i].fundingThreshold ); } fundingPhases_[i].cumulativeFundingThreshold.add( fundingPhases_[i-1].cumulativeFundingThreshold ); } _active = true; return true; } /** * @notice Allows the creator to withdraw a round of funding. * @dev The withdraw function should be called after each funding round * has been successfully filled. If the withdraw is called after the * last round has ended, the market will terminate and any * remaining funds will be sent to the market. * @return bool : The funding has successfully been transferred. */ function withdraw() external isActive() onlyWhitelistAdmin() returns(bool) { require(outstandingWithdraw_ > 0, "No funds to withdraw"); for(uint8 i; i <= totalRounds_; i++) { if(fundingPhases_[i].state == FundingState.PAID) { continue; } else if(fundingPhases_[i].state == FundingState.ENDED) { // Removes this rounds funding from the outstanding withdraw outstandingWithdraw_ = outstandingWithdraw_.sub( fundingPhases_[i].fundingThreshold ); // Sets the rounds funding to be paid fundingPhases_[i].state = FundingState.PAID; uint256 molFee = fundingPhases_[i].fundingThreshold .mul(moleculeFeeRate_) .div(moleculeFeeRate_.add(100)); // Transfers the mol fee to the molecule vault require( collateralToken_.transfer(address(moleculeVault_), molFee), "Tokens not transfer" ); // Working out the original funding goal without the mol fee uint256 creatorAmount = fundingPhases_[i].fundingThreshold .sub(molFee); // Sending the creator their collateral amount require( collateralToken_.transfer(msg.sender, creatorAmount), "Tokens not transfer" ); emit FundingWithdrawn(i, creatorAmount); } else { break; } } // This checks if the current round is the last round, if it is, it // terminates the market and sends all remaining funds to the market. if( fundingPhases_[currentPhase_].state == FundingState.NOT_STARTED ) { if(market_.active() && outstandingWithdraw_ == 0) { // This will transfer any remaining funding to the market terminateMarket(); } } return true; } /** * @notice Allows the market to check that the funding round(s) have not * been completed, and that the market is still open. * @dev This function will terminate the market if the time for the * round is exceeded. This will loose any funding the creator has * not withdrawn. * @param _receivedFunding: The amount of funding received * @return bool: Whether or not the funding is valid */ function validateFunding( uint256 _receivedFunding ) external isActive() onlyMarket() returns(bool) { require( fundingPhases_[currentPhase_].state == FundingState.STARTED, "Funding inactive" ); // Works out the time the phase should end uint256 endOfPhase = fundingPhases_[currentPhase_].startDate .addMonths(fundingPhases_[currentPhase_].phaseDuration); // Invalidates mint in market if the rounds time has expired. if(endOfPhase <= block.timestamp) { terminateMarket(); return false; } // Gets the balance of the vault against the collateral token uint256 balance = collateralToken_.balanceOf(address(this)); // Adds the fee to the funding raised for this round fundingPhases_[currentPhase_] .fundingRaised = fundingPhases_[currentPhase_] .fundingRaised.add(_receivedFunding); //injected INTEGER OVERFLOW OR UNDERFLOW // Adds received funding to the cumulative record of fee received cumulativeReceivedFee_.add(_receivedFunding); // Ensures the total fee received finishes the current round if( fundingPhases_[currentPhase_].cumulativeFundingThreshold <= cumulativeReceivedFee_ && balance.sub(outstandingWithdraw_) >= fundingPhases_[currentPhase_].fundingThreshold ) { // Ensures that the round has been funded correctly assert( fundingPhases_[currentPhase_].fundingRaised >= fundingPhases_[currentPhase_].fundingThreshold ); // end current round will check if there is excess funding and add // it to the next round, as well as incrementing the current round _endCurrentRound(); // Checks if the funding raised is larger than this rounds goal if( fundingPhases_[currentPhase_].fundingRaised > fundingPhases_[currentPhase_].fundingThreshold ) { // Ends the round _endCurrentRound(); // Ensures the received funding does not finish any other rounds do { // checks if the next funding rounds cumulative funding goal // is completed if( fundingPhases_[currentPhase_] .cumulativeFundingThreshold <= cumulativeReceivedFee_ && balance.sub(outstandingWithdraw_) >= fundingPhases_[currentPhase_].fundingThreshold ) { _endCurrentRound(); } else { break; } } while(currentPhase_ < totalRounds_); } } return true; } /** * @dev This function sends the vaults funds to the market, and sets the * outstanding withdraw to 0. * @notice If this function is called before the end of all phases, all * unclaimed (outstanding) funding will be sent to the market to be * redistributed. */ function terminateMarket() public isActive() onlyWhitelistAdmin() { uint256 remainingBalance = collateralToken_.balanceOf(address(this)); // This ensures that if the creator has any outstanding funds, that // those funds do not get sent to the market. if(outstandingWithdraw_ > 0) { remainingBalance = remainingBalance.sub(outstandingWithdraw_); } // Transfers remaining balance to the market require( collateralToken_.transfer(address(market_), remainingBalance), "Transfering of funds failed" ); // Finalizes market (stops buys/sells distributes collateral evenly) require(market_.finaliseMarket(), "Market termination error"); } /** * @notice Returns all the details (relevant to external code) for a * specific phase. * @param _phase: The phase that you want the information of * @return uint256: The funding goal (including mol tax) of the round * @return uint256: The amount of funding currently raised for the round * @return uint256: The duration of the phase * @return uint256: The timestamp of the start date of the round * @return FundingState: The enum state of the round (see IVault) */ function fundingPhase( uint256 _phase ) public view returns( uint256, uint256, uint256, uint256, FundingState ) { return ( fundingPhases_[_phase].fundingThreshold, fundingPhases_[_phase].fundingRaised, fundingPhases_[_phase].phaseDuration, fundingPhases_[_phase].startDate, fundingPhases_[_phase].state ); } /** * @return uint256: The amount of funding that the creator has earned by * not withdrawn. */ function outstandingWithdraw() public view returns(uint256) { uint256 minusMolFee = outstandingWithdraw_ .sub(outstandingWithdraw_ .mul(moleculeFeeRate_) .div(moleculeFeeRate_.add(100)) ); return minusMolFee; } /** * @dev The current active phase of funding * @return uint256: The current phase the project is in. */ function currentPhase() public view returns(uint256) { return currentPhase_; } /** * @return uint256: The total number of rounds for this project. */ function getTotalRounds() public view returns(uint256) { return totalRounds_; } /** * @return address: The address of the market that is funding this vault. */ function market() public view returns(address) { return address(market_); } /** * @return address: The address of the creator of this project. */ function creator() external view returns(address) { return creator_; } /** * @dev Ends the round, increments to the next round, rolls-over excess * funding, sets the start date of the next round, if there is one. */ function _endCurrentRound() internal { // Setting active phase state to ended fundingPhases_[currentPhase_].state = FundingState.ENDED; // Works out the excess funding for the round uint256 excess = fundingPhases_[currentPhase_] .fundingRaised.sub(fundingPhases_[currentPhase_].fundingThreshold); // If there is excess, adds it to the next round if (excess > 0) { // Adds the excess funding into the next round. fundingPhases_[currentPhase_.add(1)] .fundingRaised = fundingPhases_[currentPhase_.add(1)] .fundingRaised.add(excess); // Setting the current rounds funding raised to the threshold fundingPhases_[currentPhase_] .fundingRaised = fundingPhases_[currentPhase_].fundingThreshold; } // Adding the funished rounds funding to the outstanding withdraw. outstandingWithdraw_ = outstandingWithdraw_ .add(fundingPhases_[currentPhase_].fundingThreshold); // Incrementing the current phase currentPhase_ = currentPhase_ + 1; // Set the states the start time, starts the next round if there is one. if(fundingPhases_[currentPhase_].fundingThreshold > 0) { // Setting active phase state to Started fundingPhases_[currentPhase_].state = FundingState.STARTED; // This works out the end time of the previous round uint256 endTime = fundingPhases_[currentPhase_ .sub(1)].startDate .addMonths(fundingPhases_[currentPhase_].phaseDuration); // This works out the remaining time uint256 remaining = endTime.sub(block.timestamp); // This sets the start date to the end date of the previous round fundingPhases_[currentPhase_].startDate = block.timestamp .add(remaining); } emit PhaseFinalised( currentPhase_.sub(1), fundingPhases_[currentPhase_.sub(1)].fundingThreshold ); } } // import { WhitelistedRole } from "openzeppelin-solidity/contracts/access/roles/WhitelistedRole.sol"; /** * @author @veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) * @title The creation and co-ordinated storage of markets (a vault and * market). * @notice The market factory stores the addresses in the relevant registry. */ contract MarketFactory is IMarketFactory, ModifiedWhitelistAdminRole { //The molecule vault for molecule fee IMoleculeVault internal moleculeVault_; //The registry of all created markets IMarketRegistry internal marketRegistry_; //The registry of all curve types ICurveRegistry internal curveRegistry_; //The ERC20 collateral token contract address IERC20 internal collateralToken_; // Address of market deployer address internal marketCreator_; // The init function can only be called once bool internal isInitialized_ = false; event NewApiAddressAdded(address indexed oldAddress, address indexed newAddress); modifier onlyAnAdmin() { require(isInitialized_, "Market factory has not been activated"); require( isWhitelistAdmin(msg.sender) || msg.sender == marketCreator_, "Functionality restricted to whitelisted admin" ); _; } /** * @dev Sets variables for market deployments. * @param _collateralToken Address of the ERC20 collateral token * @param _moleculeVault The address of the molecule fee vault * @param _marketRegistry Address of the registry of all markets * @param _curveRegistry Address of the registry of all curve types * funding rounds. */ constructor( address _collateralToken, address _moleculeVault, address _marketRegistry, address _curveRegistry ) ModifiedWhitelistAdminRole() public { collateralToken_ = IERC20(_collateralToken); moleculeVault_ = IMoleculeVault(_moleculeVault); marketRegistry_ = IMarketRegistry(_marketRegistry); curveRegistry_ = ICurveRegistry(_curveRegistry); } /** * @notice Inits the market factory * @param _admin The address of the admin contract manager * @param _api The address of the backend market deployer */ function init( address _admin, address _api ) onlyWhitelistAdmin() public { super.addNewInitialAdmin(_admin); marketCreator_ = _api; super.renounceWhitelistAdmin(); isInitialized_ = true; } function updateApiAddress( address _newApiPublicKey ) onlyWhitelistAdmin() public returns(address) { address oldMarketCreator = marketCreator_; marketCreator_ = _newApiPublicKey; emit NewApiAddressAdded(oldMarketCreator, marketCreator_); return _newApiPublicKey; } /** * @notice This function allows for the creation of a new market, * consisting of a curve and vault. If the creator address is the * same as the deploying address the market the initialization of * the market will fail. * @dev Vyper cannot handle arrays of unknown length, and thus the * funding goals and durations will only be stored in the vault, * which is Solidity. * @param _fundingGoals This is the amount wanting to be raised in each * round, in collateral. * @param _phaseDurations The time for each round in months. This number * is covered into block time within the vault. * @param _creator Address of the researcher. * @param _curveType Curve selected. * @param _feeRate The percentage of fee. e.g: 60 */ function deployMarket( uint256[] calldata _fundingGoals, uint256[] calldata _phaseDurations, address _creator, uint256 _curveType, uint256 _feeRate ) external onlyAnAdmin() { // Breaks down the return of the curve data (address curveLibrary,, bool curveState) = curveRegistry_.getCurveData( _curveType ); require(_feeRate > 0, "Fee rate too low"); require(_feeRate < 100, "Fee rate too high"); require(_creator != address(0), "Creator address invalid"); require(curveState, "Curve inactive"); require(curveLibrary != address(0), "Curve library invalid"); address newVault = address(new Vault( _fundingGoals, _phaseDurations, _creator, address(collateralToken_), address(moleculeVault_) )); address newMarket = address(new Market( _feeRate, newVault, curveLibrary, address(collateralToken_) )); require(Vault(newVault).initialize(newMarket), "Vault not initialized"); marketRegistry_.registerMarket(newMarket, newVault, _creator); } /** * @notice This function will only affect new markets, and will not update * already created markets. This can only be called by an admin */ function updateMoleculeVault( address _newMoleculeVault ) public onlyWhitelistAdmin() { moleculeVault_ = IMoleculeVault(_newMoleculeVault); } /** * @return address: The address of the molecule vault */ function moleculeVault() public view returns(address) { return address(moleculeVault_); } /** * @return address: The contract address of the market registry. */ function marketRegistry() public view returns(address) { return address(marketRegistry_); } /** * @return address: The contract address of the curve registry */ function curveRegistry() public view returns(address) { return address(curveRegistry_); } /** * @return address: The contract address of the collateral token */ function collateralToken() public view returns(address) { return address(collateralToken_); } }
@veronicaLC (Veronica Coutts) & @RyRy79261 (Ryan Nobel) Market/ Emitted when a spender is approved Emitted when a transfer, mint or burn occurs Emitted when tokens are minted Emitted when tokens are burnt Emitted when the market is terminated
interface IMarket { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint value); event Mint( ); event Burn( ); event MarketTerminated(); function approve(address _spender, uint256 _value) external returns (bool); function burn(uint256 _numTokens) external returns(bool); function mint(address _to, uint256 _numTokens) external returns(bool); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom( address _from, address _to, uint256 _value ) external returns(bool); function finaliseMarket() external returns(bool); function withdraw(uint256 _amount) external returns(bool); function priceToMint(uint256 _numTokens) external view returns(uint256); function rewardForBurn(uint256 _numTokens) external view returns(uint256); function collateralToTokenBuying( uint256 _collateralTokenOffered ) external view returns(uint256); function collateralToTokenSelling( uint256 _collateralTokenNeeded ) external view returns(uint256); function allowance( address _owner, address _spender ) external view returns(uint256); function balanceOf(address _owner) external view returns (uint256); function poolBalance() external view returns (uint256); function totalSupply() external view returns (uint256); function feeRate() external view returns(uint256); function decimals() external view returns(uint256); function active() external view returns(bool); }
12,535,520
// Sources flattened with hardhat v2.6.6 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {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) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract 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; } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.6.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); } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.6.2; /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File deps/@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ 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 returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 { _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[42] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract 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 returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File deps/@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File deps/@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.6.0; /** * @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 AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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 Return all members of a role /// @dev No ordering guarantees, as per underlying EnumerableSet sturcture function getRoleMembers(bytes32 role) public view returns (address[] memory) { uint256 length = getRoleMemberCount(role); address[] memory members = new address[](length); for (uint256 i = 0; i < length; i++) { members[i] = getRoleMember(role, i); } return members; } /** * @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) internal { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[2] private __gap; } // File contracts/ICore.sol pragma solidity ^0.6.0; interface ICore { function mint( uint256 btc, address account, bytes32[] calldata merkleProof ) external returns (uint256); function redeem(uint256 btc, address account) external returns (uint256); function btcToBbtc(uint256 btc) external view returns (uint256, uint256); function bBtcToBtc(uint256 bBtc) external view returns (uint256 btc, uint256 fee); function pricePerShare() external view returns (uint256); function setGuestList(address guestlist) external; function collectFee() external; function owner() external view returns (address); } // File contracts/WrappedIbbtcEth.sol pragma solidity ^0.6.12; /* Wrapped Interest-Bearing Bitcoin (Ethereum mainnet variant) */ contract WrappedIbbtcEth is Initializable, ERC20Upgradeable, PausableUpgradeable, AccessControlUpgradeable { IERC20Upgradeable public ibbtc; ICore public core; uint256 public pricePerShare; // Allowlist bytes32 public constant ALLOWLIST_MANAGER_ROLE = keccak256("ALLOWLIST_MANAGER_ROLE"); bytes32 public constant APPROVED_ACCOUNT_ROLE = keccak256("APPROVED_ACCOUNT_ROLE"); // Pausing bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant UNPAUSER_ROLE = keccak256("UNPAUSER_ROLE"); event SetCore(address core); /// Initialize access control after creation. Function is intended to be called once and then upgraded away in a future iteration. function initializeAccessControl() external { require(msg.sender == 0xDA25ee226E534d868f0Dd8a459536b03fEE9079b); // dev: only verified deployer // vault is admin, can grant and revoke other roles _setupRole(DEFAULT_ADMIN_ROLE, 0xB65cef03b9B89f99517643226d76e286ee999e77); _setupRole(DEFAULT_ADMIN_ROLE, 0xDA25ee226E534d868f0Dd8a459536b03fEE9079b); // vault and techOps can approve account access _setupRole(ALLOWLIST_MANAGER_ROLE, 0xB65cef03b9B89f99517643226d76e286ee999e77); _setupRole(ALLOWLIST_MANAGER_ROLE, 0x86cbD0ce0c087b482782c181dA8d191De18C8275); _setupRole(ALLOWLIST_MANAGER_ROLE, 0xDA25ee226E534d868f0Dd8a459536b03fEE9079b); // vault, techOps, and guardian can pause _setupRole(PAUSER_ROLE, 0xB65cef03b9B89f99517643226d76e286ee999e77); _setupRole(PAUSER_ROLE, 0x86cbD0ce0c087b482782c181dA8d191De18C8275); _setupRole(PAUSER_ROLE, 0x6615e67b8B6b6375D38A0A3f937cd8c1a1e96386); // vault and techOps can unpause _setupRole(UNPAUSER_ROLE, 0xB65cef03b9B89f99517643226d76e286ee999e77); _setupRole(UNPAUSER_ROLE, 0x86cbD0ce0c087b482782c181dA8d191De18C8275); // allowlist_managers (vault, techOps) can use normal grantRole() to add approved accounts _setRoleAdmin(APPROVED_ACCOUNT_ROLE, ALLOWLIST_MANAGER_ROLE); } function initialize(address _ibbtc, address _core) public initializer { require(msg.sender == 0xDA25ee226E534d868f0Dd8a459536b03fEE9079b); // dev: only verified deployer __ERC20_init("Wrapped Interest-Bearing Bitcoin", "wibBTC"); core = ICore(_core); ibbtc = IERC20Upgradeable(_ibbtc); _setPricePerShare(); emit SetCore(_core); } modifier onlyAdmin { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "onlyAdmin"); _; } modifier onlyPauser { require(hasRole(PAUSER_ROLE, msg.sender), "onlyPauser"); _; } modifier onlyUnpauser { require(hasRole(UNPAUSER_ROLE, msg.sender), "onlyUnpauser"); _; } modifier onlyApprovedAccount { require(hasRole(APPROVED_ACCOUNT_ROLE, msg.sender), "onlyApprovedAccount"); _; } /// ===== Permissioned: Governance ===== function pause() external onlyPauser { _pause(); } function unpause() external onlyUnpauser { _unpause(); } /// ===== Permissionless Calls ===== /// @dev Deposit ibBTC to mint wibBTC shares function mint(uint256 _shares) external whenNotPaused onlyApprovedAccount { if (_shares == 0) { return; } require(ibbtc.transferFrom(_msgSender(), address(this), _shares)); _mint(_msgSender(), _shares); } /// @dev Redeem wibBTC for ibBTC. Denominated in shares. function burn(uint256 _shares) external whenNotPaused onlyApprovedAccount { if (_shares == 0) { return; } _burn(_msgSender(), _shares); require(ibbtc.transfer(_msgSender(), _shares)); } /// ===== ERC20Upgradeable Overrides ===== /** * @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 override whenNotPaused onlyApprovedAccount returns (bool) { /// The _balances mapping represents the underlying ibBTC shares ("non-rebased balances") /// Some naming confusion emerges due to maintaining original ERC20 var names if (amount == 0) { return true; } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @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 override whenNotPaused onlyApprovedAccount returns (bool) { /// The _balances mapping represents the underlying ibBTC shares ("non-rebased balances") /// Some naming confusion emerges due to maintaining original ERC20 var names if (amount == 0) { return true; } _transfer(_msgSender(), recipient, 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`. * - `amount` must be in shares */ function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 shares = balanceToShares(amount); _balances[sender] = _balances[sender].sub(shares, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(shares); 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 shares) internal override { require(account != address(0), "ERC20: mint to the zero address"); uint256 amount = sharesToBalance(shares); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(shares); _balances[account] = _balances[account].add(shares); 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 shares) internal override { require(account != address(0), "ERC20: burn from the zero address"); uint256 amount = sharesToBalance(shares); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(shares, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(shares); emit Transfer(account, address(0), amount); } /// @dev Static ibBTC price from core function _setPricePerShare() internal { pricePerShare = core.pricePerShare(); } /// ===== View Methods ===== /// @dev Wrapped ibBTC shares of account function sharesOf(address account) public view returns (uint256) { return _balances[account]; } /// @dev Current account shares * pricePerShare function balanceOf(address account) public view override returns (uint256) { return sharesOf(account).mul(pricePerShare).div(1e18); } /// @dev Total wrapped ibBTC shares function totalShares() public view returns (uint256) { return _totalSupply; } /// @dev Current total shares * pricePerShare function totalSupply() public view override returns (uint256) { return totalShares().mul(pricePerShare).div(1e18); } function balanceToShares(uint256 balance) public view returns (uint256) { return balance.mul(1e18).div(pricePerShare); } function sharesToBalance(uint256 shares) public view returns (uint256) { return shares.mul(pricePerShare).div(1e18); } }
Total wrapped ibBTC shares
function totalShares() public view returns (uint256) { return _totalSupply; }
1,369,532
./full_match/1/0xCDAD0ad4DD1F614a6502043Ef546e447b25Ffb99/sources/src/token/ERC20MintBurn.sol
Burns tokens from the caller. Callable only by one of the burner addresses. _value amount of tokens to burn. Should be less than or equal to caller balance./
function burn(uint256 _value) external virtual { require(isBurner(msg.sender), "ERC20MintBurn: not a burner"); _burn(msg.sender, _value); }
4,882,701
pragma solidity 0.6.12; 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.3._ */ 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.3._ */ 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); } } } } 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; } } 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)); } } 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); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface 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); } 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; } 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; } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library 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; } } 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()); } } } contract TokenLock is Ownable, AccessControl { using SafeMath for uint256; bool public transferEnabled = false; // indicates that token is transferable or not bool public noTokenLocked = false; // indicates all token is released or not struct TokenLockInfo { // token of `amount` cannot be moved before `time` uint256 amount; // locked amount uint256 time; // unix timestamp } struct TokenLockState { uint256 latestReleaseTime; TokenLockInfo[] tokenLocks; // multiple token locks can exist } mapping(address => TokenLockState) lockingStates; event AddTokenLock(address indexed to, uint256 time, uint256 amount); function unlockAllTokens() public onlyOwner { noTokenLocked = true; } function enableTransfer(bool _enable) public onlyOwner { transferEnabled = _enable; } // calculate the amount of tokens an address can use function getMinLockedAmount(address _addr) view public returns (uint256 locked) { uint256 i; uint256 a; uint256 t; uint256 lockSum = 0; // if the address has no limitations just return 0 TokenLockState storage lockState = lockingStates[_addr]; if (lockState.latestReleaseTime < now) { return 0; } for (i=0; i<lockState.tokenLocks.length; i++) { a = lockState.tokenLocks[i].amount; t = lockState.tokenLocks[i].time; if (t > now) { lockSum = lockSum.add(a); } } return lockSum; } function addTokenLock(address _addr, uint256 _value, uint256 _release_time) onlyOwner public { require(_addr != address(0)); require(_value > 0); require(_release_time > now); TokenLockState storage lockState = lockingStates[_addr]; // assigns a pointer. change the member value will update struct itself. if (_release_time > lockState.latestReleaseTime) { lockState.latestReleaseTime = _release_time; } lockState.tokenLocks.push(TokenLockInfo(_value, _release_time)); emit AddTokenLock(_addr, _release_time, _value); } } contract ERC777 is Context, IERC777, IERC20, TokenLock { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; mapping(bytes32=>bool) private usedHashes; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // 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 ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[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 override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view 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 returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view 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 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 override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); require(from != recipient, "Incorrected destination address"); require(canTransferIfLocked(from, amount), "address locked"); // require( !noTokenLocked, "Token Transfer Locked"); // require( !transferEnabled, "Token Transfer LockUp "); _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 override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public 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 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 override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {CUSTOM-function}. */ function multiSend(IERC777 _token, address[] memory _recipients, uint256[] memory _amount, bytes memory _data) public onlyOwner { for (uint256 i = 0; i < _recipients.length; i++) { _token.operatorSend(msg.sender, _recipients[i], _amount[i], _data, ""); } } function etherlessSend(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _signature) public onlyOwner { preSend(_token, _holder, _recipient, _amount, _data, _nonce, _signature); _token.operatorSend(_holder, _recipient, _amount, _data, ""); } function preSend(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce, bytes memory _signature) internal { // Ensure that signature contains the correct number of bytes require(_signature.length == 65, "length of signature incorrect"); bytes32 hash = hashForSend(_token, _holder, _recipient, _amount, _data, _nonce); require(!usedHashes[hash], "tokens already sent"); address signatory = signer(hash, _signature); require(signatory != address(0), "signatory is invalid"); require(signatory == _holder, "signatory is not the holder"); usedHashes[hash] = true; } /** * etherlessSend sub function */ function hashForSend(IERC777 _token, address _holder, address _recipient, uint256 _amount, bytes memory _data, uint256 _nonce) public pure returns (bytes32) { return keccak256(abi.encodePacked(_token, _holder, _recipient, _amount, _data, _nonce)); } /** * etherlessSend sub function */ function signer(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) } if (v < 27) { v += 27; } require(v == 27 || v == 28, "signature is invavlid"); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hash)); return ecrecover(prefixedHash, v, r, s); } /** * @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 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 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 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 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 override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); require(canTransferIfLocked(holder, amount), "address locked"); // require( !noTokenLocked, "Token Transfer Locked"); // require( !transferEnabled, "Token Transfer LockUp "); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _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 { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); 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 { 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(); _beforeTokenTransfer(operator, from, address(0), amount); _callTokensToSend(operator, from, address(0), amount, data, operatorData); // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(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); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(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"); } } function canTransferIfLocked(address _sender, uint256 _value) public view returns(bool) { uint256 after_math = balanceOf(_sender).sub(_value); return after_math >= getMinLockedAmount(_sender); } /** * @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 { } } contract EXT777 is ERC777 { uint256 initialSupply = 5000000000 * 10 ** 18; constructor() public ERC777("Enjoy X Travel", "EXT", new address[](0)) { _mint(msg.sender, initialSupply, "",""); } }
if the address has no limitations just return 0
function getMinLockedAmount(address _addr) view public returns (uint256 locked) { uint256 i; uint256 a; uint256 t; uint256 lockSum = 0; TokenLockState storage lockState = lockingStates[_addr]; if (lockState.latestReleaseTime < now) { return 0; } for (i=0; i<lockState.tokenLocks.length; i++) { a = lockState.tokenLocks[i].amount; t = lockState.tokenLocks[i].time; if (t > now) { lockSum = lockSum.add(a); } } return lockSum; for (i=0; i<lockState.tokenLocks.length; i++) { a = lockState.tokenLocks[i].amount; t = lockState.tokenLocks[i].time; if (t > now) { lockSum = lockSum.add(a); } } return lockSum; }
7,382,198
pragma solidity ^0.5.16; import "./ComptrollerInterface.sol"; import "./CTokenInterfaces.sol"; import "./ErrorReporter.sol"; import "./Exponential.sol"; import "./EIP20Interface.sol"; import "./InterestRateModel.sol"; /** * @title tropykus CToken Contract * @notice Abstract base for CTokens * @author tropykus */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize( ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint256 initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_ ) public { require(msg.sender == admin, "T1"); require(accrualBlockNumber == 0 && borrowIndex == 0, "T2"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "T3"); // Set the comptroller uint256 err = _setComptroller(comptroller_); require(err == uint256(Error.NO_ERROR), "T4"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint256(Error.NO_ERROR), "T5"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens( address spender, address src, address dst, uint256 tokens ) internal returns (uint256) { /* Fail if transfer not allowed */ uint256 allowed = comptroller.transferAllowed( address(this), src, dst, tokens ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed ); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint256 startingAllowance = 0; if (spender == src) { startingAllowance = uint256(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint256 allowanceNew; uint256 srcTokensNew; uint256 dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src].tokens, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst].tokens, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src].tokens = srcTokensNew; accountTokens[dst].tokens = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint256(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // comptroller.transferVerify(address(this), src, dst, tokens); return uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner].tokens; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint256) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint256 balance) = mulScalarTruncate( exchangeRate, accountTokens[owner].tokens ); require(mErr == MathError.NO_ERROR, "T6"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ) { uint256 cTokenBalance = accountTokens[account].tokens; uint256 borrowBalance; uint256 exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint256(Error.MATH_ERROR), 0, 0, 0); } return ( uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa ); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint256) { return interestRateModel.getBorrowRate( getCashPrior(), totalBorrows, totalReserves ); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint256) { return interestRateModel.getSupplyRate( getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa ); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "T7"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "T7"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint256) { (MathError err, uint256 result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "T8"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint256) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint256 principalTimesIndex; uint256 result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt( borrowSnapshot.principal, borrowIndex ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt( principalTimesIndex, borrowSnapshot.interestIndex ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } function getBorrowerPrincipalStored(address account) public view returns (uint256 borrowed) { borrowed = accountBorrows[account].principal; } function getSupplierSnapshotStored(address account) public view returns ( uint256 tokens, uint256 underlyingAmount, uint256 suppliedAt, uint256 promisedSupplyRate ) { tokens = accountTokens[account].tokens; underlyingAmount = accountTokens[account].underlyingAmount; suppliedAt = accountTokens[account].suppliedAt; promisedSupplyRate = accountTokens[account].promisedSupplyRate; } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint256) { require(accrueInterest() == uint256(Error.NO_ERROR), "T7"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint256) { (MathError err, uint256 result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "T9"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint256) { uint256 _totalSupply = totalSupply; if (_totalSupply == 0) { return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { MathError error; uint256 exchangeRate; uint256 totalCash = getCashPrior(); if (interestRateModel.isTropykusInterestRateModel()) { (error, exchangeRate) = tropykusExchangeRateStoredInternal( msg.sender ); if (error == MathError.NO_ERROR) { return (MathError.NO_ERROR, exchangeRate); } else { return (MathError.NO_ERROR, initialExchangeRateMantissa); } } return interestRateModel.getExchangeRate( totalCash, totalBorrows, totalReserves, totalSupply ); } } struct TropykusLocalVars { MathError mathErr; uint256 promisedSupplyRate; uint256 delta; Exp interestFactor; uint256 currentUnderlying; Exp redeemerUnderlying; Exp realAmount; Exp exchangeRate; } function tropykusExchangeRateStoredInternal(address redeemer) internal view returns (MathError, uint256) { if (totalSupply == 0) { return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { TropykusLocalVars memory vars; SupplySnapshot storage supplySnapshot = accountTokens[redeemer]; if (supplySnapshot.suppliedAt == 0) { return (MathError.DIVISION_BY_ZERO, 0); } if (supplySnapshot.tokens == 0) { return (MathError.NO_ERROR, initialExchangeRateMantissa); } (MathError err, , , uint256 exchangeRateMantissa, ) = tropykusInterestAccrued( redeemer ); if (err != MathError.NO_ERROR) return (err, 0); return (MathError.NO_ERROR, exchangeRateMantissa); } } function tropykusInterestAccrued(address account) public view returns ( MathError, uint256, uint256, uint256, uint256 ) { TropykusLocalVars memory vars; SupplySnapshot storage supplySnapshot = accountTokens[account]; vars.promisedSupplyRate = supplySnapshot.promisedSupplyRate; Exp memory expectedSupplyRatePerBlock = Exp({ mantissa: vars.promisedSupplyRate }); (vars.mathErr, vars.delta) = subUInt( accrualBlockNumber, supplySnapshot.suppliedAt ); if (vars.mathErr != MathError.NO_ERROR) return (vars.mathErr, 0, 0, initialExchangeRateMantissa, 0); Exp memory expectedSupplyRatePerBlockWithDelta; (vars.mathErr, expectedSupplyRatePerBlockWithDelta) = mulScalar( expectedSupplyRatePerBlock, vars.delta ); if (vars.mathErr != MathError.NO_ERROR) return (vars.mathErr, 0, 0, initialExchangeRateMantissa, 0); (vars.mathErr, vars.interestFactor) = addExp( Exp({mantissa: 1e18}), expectedSupplyRatePerBlockWithDelta ); vars.currentUnderlying = supplySnapshot.underlyingAmount; vars.redeemerUnderlying = Exp({mantissa: vars.currentUnderlying}); (vars.mathErr, vars.realAmount) = mulExp(vars.interestFactor, vars.redeemerUnderlying); if (vars.mathErr != MathError.NO_ERROR) return (vars.mathErr, 0, 0, initialExchangeRateMantissa, 0); uint256 interestEarned; (vars.mathErr, interestEarned) = subUInt( vars.realAmount.mantissa, vars.currentUnderlying ); if (vars.mathErr != MathError.NO_ERROR) return (vars.mathErr, 0, 0, initialExchangeRateMantissa, 0); (vars.mathErr, vars.exchangeRate) = getExp( vars.realAmount.mantissa, supplySnapshot.tokens ); if (vars.mathErr != MathError.NO_ERROR) return (vars.mathErr, 0, 0, initialExchangeRateMantissa, 0); return ( MathError.NO_ERROR, vars.interestFactor.mantissa, interestEarned, vars.exchangeRate.mantissa, vars.realAmount.mantissa ); } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint256) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint256) { /* Remember the initial block number */ uint256 currentBlockNumber = getBlockNumber(); uint256 accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint256(Error.NO_ERROR); } /* Read the previous values out of storage */ uint256 cashPrior = getCashPrior(); uint256 borrowsPrior = totalBorrows; uint256 reservesPrior = totalReserves; uint256 borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint256 borrowRateMantissa = interestRateModel.getBorrowRate( cashPrior, borrowsPrior, reservesPrior ); require(borrowRateMantissa <= borrowRateMaxMantissa, "T10"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint256 blockDelta) = subUInt( currentBlockNumber, accrualBlockNumberPrior ); require(mathErr == MathError.NO_ERROR, "T11"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint256 interestAccumulated; uint256 totalBorrowsNew; uint256 totalReservesNew; uint256 borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar( Exp({mantissa: borrowRateMantissa}), blockDelta ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, interestAccumulated) = mulScalarTruncate( simpleInterestFactor, borrowsPrior ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint256(mathErr) ); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt( Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint256(mathErr) ); } if (interestRateModel.isTropykusInterestRateModel()) { (mathErr, totalReservesNew) = newReserves( borrowRateMantissa, cashPrior, borrowsPrior, reservesPrior, interestAccumulated ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint256(mathErr) ); } } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt( simpleInterestFactor, borrowIndexPrior, borrowIndexPrior ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint256(mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest( cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew ); return uint256(Error.NO_ERROR); } function newReserves( uint256 borrowRateMantissa, uint256 cashPrior, uint256 borrowsPrior, uint256 reservesPrior, uint256 interestAccumulated ) internal view returns (MathError mathErr, uint256 totalReservesNew) { uint256 newReserveFactorMantissa; uint256 utilizationRate = interestRateModel.utilizationRate( cashPrior, borrowsPrior, reservesPrior ); uint256 expectedSupplyRate = interestRateModel.getSupplyRate( cashPrior, borrowsPrior, reservesPrior, reserveFactorMantissa ); if ( interestRateModel.isAboveOptimal( cashPrior, borrowsPrior, reservesPrior ) ) { (mathErr, newReserveFactorMantissa) = mulScalarTruncate( Exp({mantissa: utilizationRate}), borrowRateMantissa ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, newReserveFactorMantissa) = subUInt( newReserveFactorMantissa, expectedSupplyRate ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt( Exp({mantissa: newReserveFactorMantissa}), interestAccumulated, reservesPrior ); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } } else { mathErr = MathError.NO_ERROR; totalReservesNew = reservesPrior; } } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint256 mintAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return ( fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0 ); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 mintTokens; uint256 mintAmount; uint256 totalSupplyNew; uint256 accountTokensNew; uint256 actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256) { require(accountBorrows[minter].principal == 0, "T12"); /* Fail if mint not allowed */ uint256 allowed = comptroller.mintAllowed( address(this), minter, mintAmount ); if (allowed != 0) { return ( failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed ), 0 ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return ( fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0 ); } MintLocalVars memory vars; ( vars.mathErr, vars.exchangeRateMantissa ) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return ( failOpaque( Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr) ), 0 ); } vars.mintAmount = mintAmount; mintInternalVerifications(minter, vars); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate( vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}) ); require(vars.mathErr == MathError.NO_ERROR, "T13"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt( totalSupply, vars.mintTokens ); require(vars.mathErr == MathError.NO_ERROR, "T14"); (vars.mathErr, vars.accountTokensNew) = addUInt( accountTokens[minter].tokens, vars.mintTokens ); require(vars.mathErr == MathError.NO_ERROR, "T15"); uint256 currentSupplyRate = interestRateModel.getSupplyRate( getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa ); bool isTropykusInterestRateModel = interestRateModel .isTropykusInterestRateModel(); if (accountTokens[minter].tokens > 0) { Exp memory updatedUnderlying; if (isTropykusInterestRateModel) { (, , , , uint256 realAmount) = tropykusInterestAccrued(minter); updatedUnderlying = Exp({mantissa: realAmount}); } else { uint256 currentTokens = accountTokens[minter].tokens; MathError mErrorUpdatedUnderlying; (mErrorUpdatedUnderlying, updatedUnderlying) = mulExp( Exp({mantissa: currentTokens}), Exp({mantissa: vars.exchangeRateMantissa}) ); if (mErrorUpdatedUnderlying != MathError.NO_ERROR) { return ( failOpaque( Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_CALCULATION_FAILED, uint256(mErrorUpdatedUnderlying) ), 0 ); } } (, mintAmount) = addUInt(updatedUnderlying.mantissa, mintAmount); } /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = SupplySnapshot({ tokens: vars.accountTokensNew, underlyingAmount: mintAmount, suppliedAt: accrualBlockNumber, promisedSupplyRate: currentSupplyRate }); /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint256(Error.NO_ERROR), vars.actualMintAmount); } function mintInternalVerifications( address minter, MintLocalVars memory vars ) internal { minter; vars; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint256 redeemTokens) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint256 exchangeRateMantissa; uint256 redeemTokens; uint256 redeemAmount; uint256 totalSupplyNew; uint256 accountTokensNew; uint256 newSubsidyFund; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh( address payable redeemer, uint256 redeemTokensIn, uint256 redeemAmountIn ) internal returns (uint256) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "T16"); RedeemLocalVars memory vars; SupplySnapshot storage supplySnapshot = accountTokens[redeemer]; /* exchangeRate = invoke Exchange Rate Stored() */ ( vars.mathErr, vars.exchangeRateMantissa ) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint256(vars.mathErr) ); } uint256 interestEarned; uint256 subsidyFundPortion; uint256 realAmount; uint256 currentUnderlying; bool isTropykusInterestRateModel = interestRateModel .isTropykusInterestRateModel(); if (isTropykusInterestRateModel) { (, , interestEarned, , realAmount) = tropykusInterestAccrued( redeemer ); supplySnapshot.underlyingAmount = realAmount; currentUnderlying = supplySnapshot.underlyingAmount; } supplySnapshot.promisedSupplyRate = interestRateModel.getSupplyRate( getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa ); if ( isTropykusInterestRateModel && !interestRateModel.isAboveOptimal( getCashPrior(), totalBorrows, totalReserves ) ) { uint256 borrowRate = interestRateModel.getBorrowRate( getCashPrior(), totalBorrows, totalReserves ); uint256 utilizationRate = interestRateModel.utilizationRate( getCashPrior(), totalBorrows, totalReserves ); (, uint256 estimatedEarning) = mulScalarTruncate( Exp({mantissa: borrowRate}), utilizationRate ); (, subsidyFundPortion) = subUInt( supplySnapshot.promisedSupplyRate, estimatedEarning ); (, Exp memory subsidyFactor) = getExp( subsidyFundPortion, supplySnapshot.promisedSupplyRate ); (, subsidyFundPortion) = mulScalarTruncate( subsidyFactor, interestEarned ); } if (redeemAmountIn == uint256(-1)) { (, vars.redeemAmount) = mulScalarTruncate( Exp({mantissa: vars.exchangeRateMantissa}), supplySnapshot.tokens ); redeemAmountIn = vars.redeemAmount; } else { vars.redeemAmount = redeemAmountIn; } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { vars.redeemTokens = redeemTokensIn; if (isTropykusInterestRateModel) { if (redeemTokensIn == supplySnapshot.tokens) { vars.redeemAmount = supplySnapshot.underlyingAmount; } else { (, Exp memory num) = mulExp( vars.redeemTokens, currentUnderlying ); (, Exp memory realUnderlyingWithdrawAmount) = getExp( num.mantissa, supplySnapshot.tokens ); vars.redeemAmount = realUnderlyingWithdrawAmount.mantissa; } } else { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ (vars.mathErr, vars.redeemAmount) = mulScalarTruncate( Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr) ); } } } else { vars.redeemAmount = redeemAmountIn; if (isTropykusInterestRateModel) { (, Exp memory num) = mulExp( vars.redeemAmount, supplySnapshot.tokens ); (, Exp memory realTokensWithdrawAmount) = getExp( num.mantissa, currentUnderlying ); vars.redeemTokens = realTokensWithdrawAmount.mantissa; } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate( redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}) ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint256(vars.mathErr) ); } } } /* Fail if redeem not allowed */ uint256 allowed = comptroller.redeemAllowed( address(this), redeemer, vars.redeemTokens ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK ); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt( totalSupply, vars.redeemTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr) ); } (, vars.newSubsidyFund) = subUInt(subsidyFund, subsidyFundPortion); (vars.mathErr, vars.accountTokensNew) = subUInt( supplySnapshot.tokens, vars.redeemTokens ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } uint256 cash = getCashPrior(); /* Fail gracefully if protocol has insufficient cash */ if (isTropykusInterestRateModel) { cash = address(this).balance; } if (cash < vars.redeemAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; subsidyFund = vars.newSubsidyFund; supplySnapshot.tokens = vars.accountTokensNew; supplySnapshot.suppliedAt = accrualBlockNumber; (, supplySnapshot.underlyingAmount) = subUInt( supplySnapshot.underlyingAmount, vars.redeemAmount ); /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify( address(this), redeemer, vars.redeemAmount, vars.redeemTokens ); return uint256(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint256 borrowAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint256 borrowAmount) internal returns (uint256) { /* Fail if borrow not allowed */ uint256 allowed = comptroller.borrowAllowed( address(this), borrower, borrowAmount ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK ); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE ); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal( borrower ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.accountBorrowsNew) = addUInt( vars.accountBorrows, borrowAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo .BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } (vars.mathErr, vars.totalBorrowsNew) = addUInt( totalBorrows, borrowAmount ); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ); } vars = borrowInternalValidations(borrower, vars); ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow( borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew ); /* We call the defense hook */ // unused function // comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint256(Error.NO_ERROR); } function borrowInternalValidations( address borrower, BorrowLocalVars memory vars ) internal returns (BorrowLocalVars memory) { borrower; return vars; } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint256 repayAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return ( fail( Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED ), 0 ); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint256 repayAmount) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return ( fail( Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED ), 0 ); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint256 repayAmount; uint256 borrowerIndex; uint256 accountBorrows; uint256 accountBorrowsNew; uint256 totalBorrowsNew; uint256 actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh( address payer, address borrower, uint256 repayAmount ) internal returns (uint256, uint256) { /* Fail if repayBorrow not allowed */ uint256 allowed = comptroller.repayBorrowAllowed( address(this), payer, borrower, repayAmount ); if (allowed != 0) { return ( failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed ), 0 ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return ( fail( Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK ), 0 ); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal( borrower ); if (vars.mathErr != MathError.NO_ERROR) { return ( failOpaque( Error.MATH_ERROR, FailureInfo .REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr) ), 0 ); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint256(-1)) { vars.repayAmount = vars.accountBorrows; vars.actualRepayAmount = doTransferIn( payer, vars.repayAmount, true ); } else { vars.repayAmount = repayAmount; vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt( vars.accountBorrows, vars.actualRepayAmount ); require(vars.mathErr == MathError.NO_ERROR, "T17"); (vars.mathErr, vars.totalBorrowsNew) = subUInt( totalBorrows, vars.actualRepayAmount ); require(vars.mathErr == MathError.NO_ERROR, "T18"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow( payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew ); /* We call the defense hook */ // unused function // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint256(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal( address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal nonReentrant returns (uint256, uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return ( fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED ), 0 ); } error = cTokenCollateral.accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return ( fail( Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED ), 0 ); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh( msg.sender, borrower, repayAmount, cTokenCollateral ); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh( address liquidator, address borrower, uint256 repayAmount, CTokenInterface cTokenCollateral ) internal returns (uint256, uint256) { /* Fail if liquidate not allowed */ uint256 allowed = comptroller.liquidateBorrowAllowed( address(this), address(cTokenCollateral), liquidator, borrower, repayAmount ); if (allowed != 0) { return ( failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed ), 0 ); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return ( fail( Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK ), 0 ); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return ( fail( Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK ), 0 ); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return ( fail( Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER ), 0 ); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return ( fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO ), 0 ); } /* Fail if repayAmount = -1 */ if (repayAmount == uint256(-1)) { return ( fail( Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX ), 0 ); } /* Fail if repayBorrow fails */ ( uint256 repayBorrowError, uint256 actualRepayAmount ) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint256(Error.NO_ERROR)) { return ( fail( Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED ), 0 ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint256 amountSeizeError, uint256 seizeTokens) = comptroller .liquidateCalculateSeizeTokens( address(this), address(cTokenCollateral), actualRepayAmount ); require(amountSeizeError == uint256(Error.NO_ERROR), "T19"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "T20"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint256 seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal( address(this), liquidator, borrower, seizeTokens ); } else { seizeError = cTokenCollateral.seize( liquidator, borrower, seizeTokens ); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint256(Error.NO_ERROR), "T21"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow( liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens ); /* We call the defense hook */ // unused function // comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint256(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize( address liquidator, address borrower, uint256 seizeTokens ) external nonReentrant returns (uint256) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal( address seizerToken, address liquidator, address borrower, uint256 seizeTokens ) internal returns (uint256) { /* Fail if seize not allowed */ uint256 allowed = comptroller.seizeAllowed( address(this), seizerToken, liquidator, borrower, seizeTokens ); if (allowed != 0) { return failOpaque( Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed ); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail( Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER ); } MathError mathErr; uint256 borrowerTokensNew; uint256 liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt( accountTokens[borrower].tokens, seizeTokens ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(mathErr) ); } (mathErr, liquidatorTokensNew) = addUInt( accountTokens[liquidator].tokens, seizeTokens ); if (mathErr != MathError.NO_ERROR) { return failOpaque( Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(mathErr) ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower].tokens = borrowerTokensNew; accountTokens[liquidator].tokens = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint256(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) { // Check caller = admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK ); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint256) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail( Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK ); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint256(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK ); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "T22"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail( Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED ); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) { // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK ); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK ); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail( Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK ); } uint256 oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor( oldReserveFactorMantissa, newReserveFactorMantissa ); return uint256(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint256 addAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail( Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED ); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256) { // totalReserves + actualAddAmount uint256 totalReservesNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return ( fail( Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK ), actualAddAmount ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "T23"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } function _addSubsidyInternal(uint256 addAmount) internal nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_SUBSIDY_FUND_FAILED); } (error, ) = _addSubsidyFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addSubsidyFresh(uint256 addAmount) internal returns (uint256, uint256) { // subsidyFund + actualAddAmount uint256 subsidyFundNew; uint256 actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return ( fail( Error.MARKET_NOT_FRESH, FailureInfo.ADD_SUBSIDY_FUND_FRESH_CHECK ), actualAddAmount ); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); subsidyFundNew = subsidyFund + actualAddAmount; /* Revert on overflow */ require(subsidyFundNew >= subsidyFund, "T24"); // Store reserves[n+1] = reserves[n] + actualAddAmount subsidyFund = subsidyFundNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit SubsidyAdded(msg.sender, actualAddAmount, subsidyFundNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint256(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail( Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED ); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) { // totalReserves - reduceAmount uint256 totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK ); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK ); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail( Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE ); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "T25"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint256(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) { uint256 error = accrueInterest(); if (error != uint256(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail( Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED ); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail( Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK ); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail( Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK ); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "T22"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel( oldInterestRateModel, newInterestRateModel ); return uint256(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint256); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint256 amount) internal returns (uint256); function doTransferIn( address from, uint256 amount, bool isMax ) internal returns (uint256); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint256 amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "T26"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } }
Gets balance of this contract in terms of the underlying This excludes the value of the current message, if any return The quantity of underlying owned by this contract/ Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. This may revert due to insufficient balance or insufficient allowance./ Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions./ Reentrancy Guard / Prevents a contract from calling itself, directly or indirectly./
function getCashPrior() internal view returns (uint256); function doTransferIn(address from, uint256 amount) internal returns (uint256); function doTransferIn( address from, uint256 amount, bool isMax ) internal returns (uint256); function doTransferOut(address payable to, uint256 amount) internal; modifier nonReentrant() { require(_notEntered, "T26"); _notEntered = false; _; }
12,741,828
pragma solidity ^0.5.13; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "./interfaces/IValidators.sol"; import "../common/CalledByVm.sol"; import "../common/InitializableV2.sol"; import "../common/FixidityLib.sol"; import "../common/linkedlists/AddressLinkedList.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title A contract for registering and electing Validator Groups and Validators. */ contract Validators is IValidators, ICeloVersionedContract, Ownable, ReentrancyGuard, InitializableV2, UsingRegistry, UsingPrecompiles, CalledByVm { using FixidityLib for FixidityLib.Fraction; using AddressLinkedList for LinkedList.List; using SafeMath for uint256; using BytesLib for bytes; // For Validators, these requirements must be met in order to: // 1. Register a validator // 2. Affiliate with and be added to a group // 3. Receive epoch payments (note that the group must meet the group requirements as well) // Accounts may de-register their Validator `duration` seconds after they were last a member of a // group, after which no restrictions on Locked Gold will apply to the account. // // For Validator Groups, these requirements must be met in order to: // 1. Register a group // 2. Add a member to a group // 3. Receive epoch payments // Note that for groups, the requirement value is multiplied by the number of members, and is // enforced for `duration` seconds after the group last had that number of members. // Accounts may de-register their Group `duration` seconds after they were last non-empty, after // which no restrictions on Locked Gold will apply to the account. struct LockedGoldRequirements { uint256 value; // In seconds. uint256 duration; } struct ValidatorGroup { bool exists; LinkedList.List members; FixidityLib.Fraction commission; FixidityLib.Fraction nextCommission; uint256 nextCommissionBlock; // sizeHistory[i] contains the last time the group contained i members. uint256[] sizeHistory; SlashingInfo slashInfo; } // Stores the epoch number at which a validator joined a particular group. struct MembershipHistoryEntry { uint256 epochNumber; address group; } // Stores the per-epoch membership history of a validator, used to determine which group // commission should be paid to at the end of an epoch. // Stores a timestamp of the last time the validator was removed from a group, used to determine // whether or not a group can de-register. struct MembershipHistory { // The key to the most recent entry in the entries mapping. uint256 tail; // The number of entries in this validators membership history. uint256 numEntries; mapping(uint256 => MembershipHistoryEntry) entries; uint256 lastRemovedFromGroupTimestamp; } struct SlashingInfo { FixidityLib.Fraction multiplier; uint256 lastSlashed; } struct PublicKeys { bytes ecdsa; bytes bls; } struct Validator { PublicKeys publicKeys; address affiliation; FixidityLib.Fraction score; MembershipHistory membershipHistory; } // Parameters that govern the calculation of validator's score. struct ValidatorScoreParameters { uint256 exponent; FixidityLib.Fraction adjustmentSpeed; } mapping(address => ValidatorGroup) private groups; mapping(address => Validator) private validators; address[] private registeredGroups; address[] private registeredValidators; LockedGoldRequirements public validatorLockedGoldRequirements; LockedGoldRequirements public groupLockedGoldRequirements; ValidatorScoreParameters private validatorScoreParameters; uint256 public membershipHistoryLength; uint256 public maxGroupSize; // The number of blocks to delay a ValidatorGroup's commission update uint256 public commissionUpdateDelay; uint256 public slashingMultiplierResetPeriod; uint256 public downtimeGracePeriod; event MaxGroupSizeSet(uint256 size); event CommissionUpdateDelaySet(uint256 delay); event ValidatorScoreParametersSet(uint256 exponent, uint256 adjustmentSpeed); event GroupLockedGoldRequirementsSet(uint256 value, uint256 duration); event ValidatorLockedGoldRequirementsSet(uint256 value, uint256 duration); event MembershipHistoryLengthSet(uint256 length); event ValidatorRegistered(address indexed validator); event ValidatorDeregistered(address indexed validator); event ValidatorAffiliated(address indexed validator, address indexed group); event ValidatorDeaffiliated(address indexed validator, address indexed group); event ValidatorEcdsaPublicKeyUpdated(address indexed validator, bytes ecdsaPublicKey); event ValidatorBlsPublicKeyUpdated(address indexed validator, bytes blsPublicKey); event ValidatorScoreUpdated(address indexed validator, uint256 score, uint256 epochScore); event ValidatorGroupRegistered(address indexed group, uint256 commission); event ValidatorGroupDeregistered(address indexed group); event ValidatorGroupMemberAdded(address indexed group, address indexed validator); event ValidatorGroupMemberRemoved(address indexed group, address indexed validator); event ValidatorGroupMemberReordered(address indexed group, address indexed validator); event ValidatorGroupCommissionUpdateQueued( address indexed group, uint256 commission, uint256 activationBlock ); event ValidatorGroupCommissionUpdated(address indexed group, uint256 commission); event ValidatorEpochPaymentDistributed( address indexed validator, uint256 validatorPayment, address indexed group, uint256 groupPayment ); modifier onlySlasher() { require(getLockedGold().isSlasher(msg.sender), "Only registered slasher can call"); _; } /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 2, 0, 1); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param groupRequirementValue The Locked Gold requirement amount for groups. * @param groupRequirementDuration The Locked Gold requirement duration for groups. * @param validatorRequirementValue The Locked Gold requirement amount for validators. * @param validatorRequirementDuration The Locked Gold requirement duration for validators. * @param validatorScoreExponent The exponent used in calculating validator scores. * @param validatorScoreAdjustmentSpeed The speed at which validator scores are adjusted. * @param _membershipHistoryLength The max number of entries for validator membership history. * @param _maxGroupSize The maximum group size. * @param _commissionUpdateDelay The number of blocks to delay a ValidatorGroup's commission * update. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 groupRequirementValue, uint256 groupRequirementDuration, uint256 validatorRequirementValue, uint256 validatorRequirementDuration, uint256 validatorScoreExponent, uint256 validatorScoreAdjustmentSpeed, uint256 _membershipHistoryLength, uint256 _slashingMultiplierResetPeriod, uint256 _maxGroupSize, uint256 _commissionUpdateDelay, uint256 _downtimeGracePeriod ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setGroupLockedGoldRequirements(groupRequirementValue, groupRequirementDuration); setValidatorLockedGoldRequirements(validatorRequirementValue, validatorRequirementDuration); setValidatorScoreParameters(validatorScoreExponent, validatorScoreAdjustmentSpeed); setMaxGroupSize(_maxGroupSize); setCommissionUpdateDelay(_commissionUpdateDelay); setMembershipHistoryLength(_membershipHistoryLength); setSlashingMultiplierResetPeriod(_slashingMultiplierResetPeriod); setDowntimeGracePeriod(_downtimeGracePeriod); } /** * @notice Sets initialized == true on implementation contracts * @param test Set to true to skip implementation initialization */ constructor(bool test) public InitializableV2(test) {} /** * @notice Updates the block delay for a ValidatorGroup's commission udpdate * @param delay Number of blocks to delay the update */ function setCommissionUpdateDelay(uint256 delay) public onlyOwner { require(delay != commissionUpdateDelay, "commission update delay not changed"); commissionUpdateDelay = delay; emit CommissionUpdateDelaySet(delay); } /** * @notice Updates the maximum number of members a group can have. * @param size The maximum group size. * @return True upon success. */ function setMaxGroupSize(uint256 size) public onlyOwner returns (bool) { require(0 < size, "Max group size cannot be zero"); require(size != maxGroupSize, "Max group size not changed"); maxGroupSize = size; emit MaxGroupSizeSet(size); return true; } /** * @notice Updates the number of validator group membership entries to store. * @param length The number of validator group membership entries to store. * @return True upon success. */ function setMembershipHistoryLength(uint256 length) public onlyOwner returns (bool) { require(0 < length, "Membership history length cannot be zero"); require(length != membershipHistoryLength, "Membership history length not changed"); membershipHistoryLength = length; emit MembershipHistoryLengthSet(length); return true; } /** * @notice Updates the validator score parameters. * @param exponent The exponent used in calculating the score. * @param adjustmentSpeed The speed at which the score is adjusted. * @return True upon success. */ function setValidatorScoreParameters(uint256 exponent, uint256 adjustmentSpeed) public onlyOwner returns (bool) { require( adjustmentSpeed <= FixidityLib.fixed1().unwrap(), "Adjustment speed cannot be larger than 1" ); require( exponent != validatorScoreParameters.exponent || !FixidityLib.wrap(adjustmentSpeed).equals(validatorScoreParameters.adjustmentSpeed), "Adjustment speed and exponent not changed" ); validatorScoreParameters = ValidatorScoreParameters( exponent, FixidityLib.wrap(adjustmentSpeed) ); emit ValidatorScoreParametersSet(exponent, adjustmentSpeed); return true; } /** * @notice Returns the maximum number of members a group can add. * @return The maximum number of members a group can add. */ function getMaxGroupSize() external view returns (uint256) { return maxGroupSize; } /** * @notice Returns the block delay for a ValidatorGroup's commission udpdate. * @return The block delay for a ValidatorGroup's commission udpdate. */ function getCommissionUpdateDelay() external view returns (uint256) { return commissionUpdateDelay; } /** * @notice Updates the Locked Gold requirements for Validator Groups. * @param value The per-member amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setGroupLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = groupLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Group requirements not changed" ); groupLockedGoldRequirements = LockedGoldRequirements(value, duration); emit GroupLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Updates the Locked Gold requirements for Validators. * @param value The amount of Locked Gold required. * @param duration The time (in seconds) that these requirements persist for. * @return True upon success. */ function setValidatorLockedGoldRequirements(uint256 value, uint256 duration) public onlyOwner returns (bool) { LockedGoldRequirements storage requirements = validatorLockedGoldRequirements; require( value != requirements.value || duration != requirements.duration, "Validator requirements not changed" ); validatorLockedGoldRequirements = LockedGoldRequirements(value, duration); emit ValidatorLockedGoldRequirementsSet(value, duration); return true; } /** * @notice Registers a validator unaffiliated with any validator group. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus, should * match the validator signer. 64 bytes. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient Locked Gold. */ function registerValidator( bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account) && !isValidatorGroup(account), "Already registered"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= validatorLockedGoldRequirements.value, "Deposit too small"); Validator storage validator = validators[account]; address signer = getAccounts().getValidatorSigner(account); require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); registeredValidators.push(account); updateMembershipHistory(account, address(0)); emit ValidatorRegistered(account); return true; } /** * @notice Returns the parameters that govern how a validator's score is calculated. * @return The parameters that goven how a validator's score is calculated. */ function getValidatorScoreParameters() external view returns (uint256, uint256) { return (validatorScoreParameters.exponent, validatorScoreParameters.adjustmentSpeed.unwrap()); } /** * @notice Returns the group membership history of a validator. * @param account The validator whose membership history to return. * @return The group membership history of a validator. */ function getMembershipHistory(address account) external view returns (uint256[] memory, address[] memory, uint256, uint256) { MembershipHistory storage history = validators[account].membershipHistory; uint256[] memory epochs = new uint256[](history.numEntries); address[] memory membershipGroups = new address[](history.numEntries); for (uint256 i = 0; i < history.numEntries; i = i.add(1)) { uint256 index = history.tail.add(i); epochs[i] = history.entries[index].epochNumber; membershipGroups[i] = history.entries[index].group; } return (epochs, membershipGroups, history.lastRemovedFromGroupTimestamp, history.tail); } /** * @notice Calculates the validator score for an epoch from the uptime value for the epoch. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev epoch_score = uptime ** exponent * @return Fixidity representation of the epoch score between 0 and 1. */ function calculateEpochScore(uint256 uptime) public view returns (uint256) { require(uptime <= FixidityLib.fixed1().unwrap(), "Uptime cannot be larger than one"); uint256 numerator; uint256 denominator; uptime = Math.min(uptime.add(downtimeGracePeriod), FixidityLib.fixed1().unwrap()); (numerator, denominator) = fractionMulExp( FixidityLib.fixed1().unwrap(), FixidityLib.fixed1().unwrap(), uptime, FixidityLib.fixed1().unwrap(), validatorScoreParameters.exponent, 18 ); return FixidityLib.newFixedFraction(numerator, denominator).unwrap(); } /** * @notice Calculates the aggregate score of a group for an epoch from individual uptimes. * @param uptimes Array of Fixidity representations of the validators' uptimes, between 0 and 1. * @dev group_score = average(uptimes ** exponent) * @return Fixidity representation of the group epoch score between 0 and 1. */ function calculateGroupEpochScore(uint256[] calldata uptimes) external view returns (uint256) { require(uptimes.length > 0, "Uptime array empty"); require(uptimes.length <= maxGroupSize, "Uptime array larger than maximum group size"); FixidityLib.Fraction memory sum; for (uint256 i = 0; i < uptimes.length; i = i.add(1)) { sum = sum.add(FixidityLib.wrap(calculateEpochScore(uptimes[i]))); } return sum.divide(FixidityLib.newFixed(uptimes.length)).unwrap(); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator account whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @return True upon success. */ function updateValidatorScoreFromSigner(address signer, uint256 uptime) external onlyVm() { _updateValidatorScoreFromSigner(signer, uptime); } /** * @notice Updates a validator's score based on its uptime for the epoch. * @param signer The validator signer of the validator whose score needs updating. * @param uptime The Fixidity representation of the validator's uptime, between 0 and 1. * @dev new_score = uptime ** exponent * adjustmentSpeed + old_score * (1 - adjustmentSpeed) * @return True upon success. */ function _updateValidatorScoreFromSigner(address signer, uint256 uptime) internal { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); FixidityLib.Fraction memory epochScore = FixidityLib.wrap(calculateEpochScore(uptime)); FixidityLib.Fraction memory newComponent = validatorScoreParameters.adjustmentSpeed.multiply( epochScore ); FixidityLib.Fraction memory currentComponent = FixidityLib.fixed1().subtract( validatorScoreParameters.adjustmentSpeed ); currentComponent = currentComponent.multiply(validators[account].score); validators[account].score = FixidityLib.wrap( Math.min(epochScore.unwrap(), newComponent.add(currentComponent).unwrap()) ); emit ValidatorScoreUpdated(account, validators[account].score.unwrap(), epochScore.unwrap()); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the account to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) external onlyVm() returns (uint256) { return _distributeEpochPaymentsFromSigner(signer, maxPayment); } /** * @notice Distributes epoch payments to the account associated with `signer` and its group. * @param signer The validator signer of the validator to distribute the epoch payment to. * @param maxPayment The maximum payment to the validator. Actual payment is based on score and * group commission. * @return The total payment paid to the validator and their group. */ function _distributeEpochPaymentsFromSigner(address signer, uint256 maxPayment) internal returns (uint256) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); // The group that should be paid is the group that the validator was a member of at the // time it was elected. address group = getMembershipInLastEpoch(account); require(group != address(0), "Validator not registered with a group"); // Both the validator and the group must maintain the minimum locked gold balance in order to // receive epoch payments. if (meetsAccountLockedGoldRequirements(account) && meetsAccountLockedGoldRequirements(group)) { FixidityLib.Fraction memory totalPayment = FixidityLib .newFixed(maxPayment) .multiply(validators[account].score) .multiply(groups[group].slashInfo.multiplier); uint256 groupPayment = totalPayment.multiply(groups[group].commission).fromFixed(); uint256 validatorPayment = totalPayment.fromFixed().sub(groupPayment); IStableToken stableToken = getStableToken(); require(stableToken.mint(group, groupPayment), "mint failed to validator group"); require(stableToken.mint(account, validatorPayment), "mint failed to validator account"); emit ValidatorEpochPaymentDistributed(account, validatorPayment, group, groupPayment); return totalPayment.fromFixed(); } else { return 0; } } /** * @notice De-registers a validator. * @param index The index of this validator in the list of all registered validators. * @return True upon success. * @dev Fails if the account is not a validator. * @dev Fails if the validator has been a member of a group too recently. */ function deregisterValidator(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); // Require that the validator has not been a member of a validator group for // `validatorLockedGoldRequirements.duration` seconds. Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { require( !groups[validator.affiliation].members.contains(account), "Has been group member recently" ); } uint256 requirementEndTime = validator.membershipHistory.lastRemovedFromGroupTimestamp.add( validatorLockedGoldRequirements.duration ); require(requirementEndTime < now, "Not yet requirement end time"); // Remove the validator. deleteElement(registeredValidators, account, index); delete validators[account]; emit ValidatorDeregistered(account); return true; } /** * @notice Affiliates a validator with a group, allowing it to be added as a member. * @param group The validator group with which to affiliate. * @return True upon success. * @dev De-affiliates with the previously affiliated group if present. */ function affiliate(address group) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); require(isValidatorGroup(group), "Not a validator group"); require(meetsAccountLockedGoldRequirements(account), "Validator doesn't meet requirements"); require(meetsAccountLockedGoldRequirements(group), "Group doesn't meet requirements"); Validator storage validator = validators[account]; if (validator.affiliation != address(0)) { _deaffiliate(validator, account); } validator.affiliation = group; emit ValidatorAffiliated(account, group); return true; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @return True upon success. * @dev Fails if the account is not a validator with non-zero affiliation. */ function deaffiliate() external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require(validator.affiliation != address(0), "deaffiliate: not affiliated"); _deaffiliate(validator, account); return true; } /** * @notice Updates a validator's BLS key. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 48 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updateBlsPublicKey(bytes calldata blsPublicKey, bytes calldata blsPop) external returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Updates a validator's BLS key. * @param validator The validator whose BLS public key should be updated. * @param account The address under which the validator is registered. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function _updateBlsPublicKey( Validator storage validator, address account, bytes memory blsPublicKey, bytes memory blsPop ) private returns (bool) { require(blsPublicKey.length == 96, "Wrong BLS public key length"); require(blsPop.length == 48, "Wrong BLS PoP length"); require(checkProofOfPossession(account, blsPublicKey, blsPop), "Invalid BLS PoP"); validator.publicKeys.bls = blsPublicKey; emit ValidatorBlsPublicKeyUpdated(account, blsPublicKey); return true; } /** * @notice Updates a validator's ECDSA key. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @return True upon success. */ function updateEcdsaPublicKey(address account, address signer, bytes calldata ecdsaPublicKey) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); return true; } /** * @notice Updates a validator's ECDSA key. * @param validator The validator whose ECDSA public key should be updated. * @param signer The address with which the validator is signing consensus messages. * @param ecdsaPublicKey The ECDSA public key that the validator is using for consensus. Should * match `signer`. 64 bytes. * @return True upon success. */ function _updateEcdsaPublicKey( Validator storage validator, address account, address signer, bytes memory ecdsaPublicKey ) private returns (bool) { require(ecdsaPublicKey.length == 64, "Wrong ECDSA public key length"); require( address(uint160(uint256(keccak256(ecdsaPublicKey)))) == signer, "ECDSA key does not match signer" ); validator.publicKeys.ecdsa = ecdsaPublicKey; emit ValidatorEcdsaPublicKeyUpdated(account, ecdsaPublicKey); return true; } /** * @notice Updates a validator's ECDSA and BLS keys. * @param account The address under which the validator is registered. * @param signer The address which the validator is using to sign consensus messages. * @param ecdsaPublicKey The ECDSA public key corresponding to `signer`. * @param blsPublicKey The BLS public key that the validator is using for consensus, should pass * proof of possession. 96 bytes. * @param blsPop The BLS public key proof-of-possession, which consists of a signature on the * account address. 48 bytes. * @return True upon success. */ function updatePublicKeys( address account, address signer, bytes calldata ecdsaPublicKey, bytes calldata blsPublicKey, bytes calldata blsPop ) external onlyRegisteredContract(ACCOUNTS_REGISTRY_ID) returns (bool) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; require( _updateEcdsaPublicKey(validator, account, signer, ecdsaPublicKey), "Error updating ECDSA public key" ); require( _updateBlsPublicKey(validator, account, blsPublicKey, blsPop), "Error updating BLS public key" ); return true; } /** * @notice Registers a validator group with no member validators. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. * @return True upon success. * @dev Fails if the account is already a validator or validator group. * @dev Fails if the account does not have sufficient weight. */ function registerValidatorGroup(uint256 commission) external nonReentrant returns (bool) { require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); address account = getAccounts().validatorSignerToAccount(msg.sender); require(!isValidator(account), "Already registered as validator"); require(!isValidatorGroup(account), "Already registered as group"); uint256 lockedGoldBalance = getLockedGold().getAccountTotalLockedGold(account); require(lockedGoldBalance >= groupLockedGoldRequirements.value, "Not enough locked gold"); ValidatorGroup storage group = groups[account]; group.exists = true; group.commission = FixidityLib.wrap(commission); group.slashInfo = SlashingInfo(FixidityLib.fixed1(), 0); registeredGroups.push(account); emit ValidatorGroupRegistered(account, commission); return true; } /** * @notice De-registers a validator group. * @param index The index of this validator group in the list of all validator groups. * @return True upon success. * @dev Fails if the account is not a validator group with no members. * @dev Fails if the group has had members too recently. */ function deregisterValidatorGroup(uint256 index) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); // Only Validator Groups that have never had members or have been empty for at least // `groupLockedGoldRequirements.duration` seconds can be deregistered. require(isValidatorGroup(account), "Not a validator group"); require(groups[account].members.numElements == 0, "Validator group not empty"); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 1) { require( sizeHistory[1].add(groupLockedGoldRequirements.duration) < now, "Hasn't been empty for long enough" ); } delete groups[account]; deleteElement(registeredGroups, account, index); emit ValidatorGroupDeregistered(account); return true; } /** * @notice Adds a member to the end of a validator group's list of members. * @param validator The validator to add to the group * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has zero members. */ function addMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements > 0, "Validator group empty"); return _addMember(account, validator, address(0), address(0)); } /** * @notice Adds the first member to a group's list of members and marks it eligible for election. * @param validator The validator to add to the group * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function addFirstMember(address validator, address lesser, address greater) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(groups[account].members.numElements == 0, "Validator group not empty"); return _addMember(account, validator, lesser, greater); } /** * @notice Adds a member to the end of a validator group's list of members. * @param group The address of the validator group. * @param validator The validator to add to the group. * @param lesser The address of the group that has received fewer votes than this group. * @param greater The address of the group that has received more votes than this group. * @return True upon success. * @dev Fails if `validator` has not set their affiliation to this account. * @dev Fails if the group has > 0 members. */ function _addMember(address group, address validator, address lesser, address greater) private returns (bool) { require(isValidatorGroup(group) && isValidator(validator), "Not validator and group"); ValidatorGroup storage _group = groups[group]; require(_group.members.numElements < maxGroupSize, "group would exceed maximum size"); require(validators[validator].affiliation == group, "Not affiliated to group"); require(!_group.members.contains(validator), "Already in group"); uint256 numMembers = _group.members.numElements.add(1); _group.members.push(validator); require(meetsAccountLockedGoldRequirements(group), "Group requirements not met"); require(meetsAccountLockedGoldRequirements(validator), "Validator requirements not met"); if (numMembers == 1) { getElection().markGroupEligible(group, lesser, greater); } updateMembershipHistory(validator, group); updateSizeHistory(group, numMembers.sub(1)); emit ValidatorGroupMemberAdded(group, validator); return true; } /** * @notice Removes a member from a validator group. * @param validator The validator to remove from the group * @return True upon success. * @dev Fails if `validator` is not a member of the account's group. */ function removeMember(address validator) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account) && isValidator(validator), "is not group and validator"); return _removeMember(account, validator); } /** * @notice Reorders a member within a validator group. * @param validator The validator to reorder. * @param lesserMember The member who will be behind `validator`, or 0 if `validator` will be the * last member. * @param greaterMember The member who will be ahead of `validator`, or 0 if `validator` will be * the first member. * @return True upon success. * @dev Fails if `validator` is not a member of the account's validator group. */ function reorderMember(address validator, address lesserMember, address greaterMember) external nonReentrant returns (bool) { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a group"); require(isValidator(validator), "Not a validator"); ValidatorGroup storage group = groups[account]; require(group.members.contains(validator), "Not a member of the group"); group.members.update(validator, lesserMember, greaterMember); emit ValidatorGroupMemberReordered(account, validator); return true; } /** * @notice Queues an update to a validator group's commission. * If there was a previously scheduled update, that is overwritten. * @param commission Fixidity representation of the commission this group receives on epoch * payments made to its members. Must be in the range [0, 1.0]. */ function setNextCommissionUpdate(uint256 commission) external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(commission <= FixidityLib.fixed1().unwrap(), "Commission can't be greater than 100%"); require(commission != group.commission.unwrap(), "Commission must be different"); group.nextCommission = FixidityLib.wrap(commission); group.nextCommissionBlock = block.number.add(commissionUpdateDelay); emit ValidatorGroupCommissionUpdateQueued(account, commission, group.nextCommissionBlock); } /** * @notice Updates a validator group's commission based on the previously queued update */ function updateCommission() external { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require(group.nextCommissionBlock != 0, "No commission update queued"); require(group.nextCommissionBlock <= block.number, "Can't apply commission update yet"); group.commission = group.nextCommission; delete group.nextCommission; delete group.nextCommissionBlock; emit ValidatorGroupCommissionUpdated(account, group.commission.unwrap()); } /** * @notice Returns the current locked gold balance requirement for the supplied account. * @param account The account that may have to meet locked gold balance requirements. * @return The current locked gold balance requirement for the supplied account. */ function getAccountLockedGoldRequirement(address account) public view returns (uint256) { if (isValidator(account)) { return validatorLockedGoldRequirements.value; } else if (isValidatorGroup(account)) { uint256 multiplier = Math.max(1, groups[account].members.numElements); uint256[] storage sizeHistory = groups[account].sizeHistory; if (sizeHistory.length > 0) { for (uint256 i = sizeHistory.length.sub(1); i > 0; i = i.sub(1)) { if (sizeHistory[i].add(groupLockedGoldRequirements.duration) >= now) { multiplier = Math.max(i, multiplier); break; } } } return groupLockedGoldRequirements.value.mul(multiplier); } return 0; } /** * @notice Returns whether or not an account meets its Locked Gold requirements. * @param account The address of the account. * @return Whether or not an account meets its Locked Gold requirements. */ function meetsAccountLockedGoldRequirements(address account) public view returns (bool) { uint256 balance = getLockedGold().getAccountTotalLockedGold(account); // Add a bit of "wiggle room" to accommodate the fact that vote activation can result in ~1 // wei rounding errors. Using 10 as an additional margin of safety. return balance.add(10) >= getAccountLockedGoldRequirement(account); } /** * @notice Returns the validator BLS key. * @param signer The account that registered the validator or its authorized signing address. * @return The validator BLS key. */ function getValidatorBlsPublicKeyFromSigner(address signer) external view returns (bytes memory blsPublicKey) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return validators[account].publicKeys.bls; } /** * @notice Returns validator information. * @param account The account that registered the validator. * @return The unpacked validator struct. */ function getValidator(address account) public view returns ( bytes memory ecdsaPublicKey, bytes memory blsPublicKey, address affiliation, uint256 score, address signer ) { require(isValidator(account), "Not a validator"); Validator storage validator = validators[account]; return ( validator.publicKeys.ecdsa, validator.publicKeys.bls, validator.affiliation, validator.score.unwrap(), getAccounts().getValidatorSigner(account) ); } /** * @notice Returns validator group information. * @param account The account that registered the validator group. * @return The unpacked validator group struct. */ function getValidatorGroup(address account) external view returns (address[] memory, uint256, uint256, uint256, uint256[] memory, uint256, uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return ( group.members.getKeys(), group.commission.unwrap(), group.nextCommission.unwrap(), group.nextCommissionBlock, group.sizeHistory, group.slashInfo.multiplier.unwrap(), group.slashInfo.lastSlashed ); } /** * @notice Returns the number of members in a validator group. * @param account The address of the validator group. * @return The number of members in a validator group. */ function getGroupNumMembers(address account) public view returns (uint256) { require(isValidatorGroup(account), "Not validator group"); return groups[account].members.numElements; } /** * @notice Returns the top n group members for a particular group. * @param account The address of the validator group. * @param n The number of members to return. * @return The top n group members for a particular group. */ function getTopGroupValidators(address account, uint256 n) external view returns (address[] memory) { address[] memory topAccounts = groups[account].members.headN(n); address[] memory topValidators = new address[](n); for (uint256 i = 0; i < n; i = i.add(1)) { topValidators[i] = getAccounts().getValidatorSigner(topAccounts[i]); } return topValidators; } /** * @notice Returns the number of members in the provided validator groups. * @param accounts The addresses of the validator groups. * @return The number of members in the provided validator groups. */ function getGroupsNumMembers(address[] calldata accounts) external view returns (uint256[] memory) { uint256[] memory numMembers = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; i = i.add(1)) { numMembers[i] = getGroupNumMembers(accounts[i]); } return numMembers; } /** * @notice Returns the number of registered validators. * @return The number of registered validators. */ function getNumRegisteredValidators() external view returns (uint256) { return registeredValidators.length; } /** * @notice Returns the Locked Gold requirements for validators. * @return The Locked Gold requirements for validators. */ function getValidatorLockedGoldRequirements() external view returns (uint256, uint256) { return (validatorLockedGoldRequirements.value, validatorLockedGoldRequirements.duration); } /** * @notice Returns the Locked Gold requirements for validator groups. * @return The Locked Gold requirements for validator groups. */ function getGroupLockedGoldRequirements() external view returns (uint256, uint256) { return (groupLockedGoldRequirements.value, groupLockedGoldRequirements.duration); } /** * @notice Returns the list of registered validator accounts. * @return The list of registered validator accounts. */ function getRegisteredValidators() external view returns (address[] memory) { return registeredValidators; } /** * @notice Returns the list of signers for the registered validator accounts. * @return The list of signers for registered validator accounts. */ function getRegisteredValidatorSigners() external view returns (address[] memory) { IAccounts accounts = getAccounts(); address[] memory signers = new address[](registeredValidators.length); for (uint256 i = 0; i < signers.length; i = i.add(1)) { signers[i] = accounts.getValidatorSigner(registeredValidators[i]); } return signers; } /** * @notice Returns the list of registered validator group accounts. * @return The list of registered validator group addresses. */ function getRegisteredValidatorGroups() external view returns (address[] memory) { return registeredGroups; } /** * @notice Returns whether a particular account has a registered validator group. * @param account The account. * @return Whether a particular address is a registered validator group. */ function isValidatorGroup(address account) public view returns (bool) { return groups[account].exists; } /** * @notice Returns whether a particular account has a registered validator. * @param account The account. * @return Whether a particular address is a registered validator. */ function isValidator(address account) public view returns (bool) { return validators[account].publicKeys.bls.length > 0; } /** * @notice Deletes an element from a list of addresses. * @param list The list of addresses. * @param element The address to delete. * @param index The index of `element` in the list. */ function deleteElement(address[] storage list, address element, uint256 index) private { require(index < list.length && list[index] == element, "deleteElement: index out of range"); uint256 lastIndex = list.length.sub(1); list[index] = list[lastIndex]; delete list[lastIndex]; list.length = lastIndex; } /** * @notice Removes a member from a validator group. * @param group The group from which the member should be removed. * @param validator The validator to remove from the group. * @return True upon success. * @dev If `validator` was the only member of `group`, `group` becomes unelectable. * @dev Fails if `validator` is not a member of `group`. */ function _removeMember(address group, address validator) private returns (bool) { ValidatorGroup storage _group = groups[group]; require(validators[validator].affiliation == group, "Not affiliated to group"); require(_group.members.contains(validator), "Not a member of the group"); _group.members.remove(validator); uint256 numMembers = _group.members.numElements; // Empty validator groups are not electable. if (numMembers == 0) { getElection().markGroupIneligible(group); } updateMembershipHistory(validator, address(0)); updateSizeHistory(group, numMembers.add(1)); emit ValidatorGroupMemberRemoved(group, validator); return true; } /** * @notice Updates the group membership history of a particular account. * @param account The account whose group membership has changed. * @param group The group that the account is now a member of. * @return True upon success. * @dev Note that this is used to determine a validator's membership at the time of an election, * and so group changes within an epoch will overwrite eachother. */ function updateMembershipHistory(address account, address group) private returns (bool) { MembershipHistory storage history = validators[account].membershipHistory; uint256 epochNumber = getEpochNumber(); uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); if (history.numEntries > 0 && group == address(0)) { history.lastRemovedFromGroupTimestamp = now; } if (history.numEntries > 0 && history.entries[head].epochNumber == epochNumber) { // There have been no elections since the validator last changed membership, overwrite the // previous entry. history.entries[head] = MembershipHistoryEntry(epochNumber, group); return true; } // There have been elections since the validator last changed membership, create a new entry. uint256 index = history.numEntries == 0 ? 0 : head.add(1); history.entries[index] = MembershipHistoryEntry(epochNumber, group); if (history.numEntries < membershipHistoryLength) { // Not enough entries, don't remove any. history.numEntries = history.numEntries.add(1); } else if (history.numEntries == membershipHistoryLength) { // Exactly enough entries, delete the oldest one to account for the one we added. delete history.entries[history.tail]; history.tail = history.tail.add(1); } else { // Too many entries, delete the oldest two to account for the one we added. delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2); } return true; } /** * @notice Updates the size history of a validator group. * @param group The account whose group size has changed. * @param size The new size of the group. * @dev Used to determine how much gold an account needs to keep locked. */ function updateSizeHistory(address group, uint256 size) private { uint256[] storage sizeHistory = groups[group].sizeHistory; if (size == sizeHistory.length) { sizeHistory.push(now); } else if (size < sizeHistory.length) { sizeHistory[size] = now; } else { require(false, "Unable to update size history"); } } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param signer The signer of the account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpochFromSigner(address signer) external view returns (address) { address account = getAccounts().signerToAccount(signer); require(isValidator(account), "Not a validator"); return getMembershipInLastEpoch(account); } /** * @notice Returns the group that `account` was a member of at the end of the last epoch. * @param account The account whose group membership should be returned. * @return The group that `account` was a member of at the end of the last epoch. */ function getMembershipInLastEpoch(address account) public view returns (address) { uint256 epochNumber = getEpochNumber(); MembershipHistory storage history = validators[account].membershipHistory; uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); // If the most recent entry in the membership history is for the current epoch number, we need // to look at the previous entry. if (history.entries[head].epochNumber == epochNumber) { if (head > history.tail) { head = head.sub(1); } } return history.entries[head].group; } /** * @notice De-affiliates a validator, removing it from the group for which it is a member. * @param validator The validator to deaffiliate from their affiliated validator group. * @param validatorAccount The LockedGold account of the validator. * @return True upon success. */ function _deaffiliate(Validator storage validator, address validatorAccount) private returns (bool) { address affiliation = validator.affiliation; ValidatorGroup storage group = groups[affiliation]; if (group.members.contains(validatorAccount)) { _removeMember(affiliation, validatorAccount); } validator.affiliation = address(0); emit ValidatorDeaffiliated(validatorAccount, affiliation); return true; } /** * @notice Removes a validator from the group for which it is a member. * @param validatorAccount The validator to deaffiliate from their affiliated validator group. */ function forceDeaffiliateIfValidator(address validatorAccount) external nonReentrant onlySlasher { if (isValidator(validatorAccount)) { Validator storage validator = validators[validatorAccount]; if (validator.affiliation != address(0)) { _deaffiliate(validator, validatorAccount); } } } /** * @notice Sets the slashingMultiplierRestPeriod property if called by owner. * @param value New reset period for slashing multiplier. */ function setSlashingMultiplierResetPeriod(uint256 value) public nonReentrant onlyOwner { slashingMultiplierResetPeriod = value; } /** * @notice Sets the downtimeGracePeriod property if called by owner. * @param value New downtime grace period for calculating epoch scores. */ function setDowntimeGracePeriod(uint256 value) public nonReentrant onlyOwner { downtimeGracePeriod = value; } /** * @notice Resets a group's slashing multiplier if it has been >= the reset period since * the last time the group was slashed. */ function resetSlashingMultiplier() external nonReentrant { address account = getAccounts().validatorSignerToAccount(msg.sender); require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; require( now >= group.slashInfo.lastSlashed.add(slashingMultiplierResetPeriod), "`resetSlashingMultiplier` called before resetPeriod expired" ); group.slashInfo.multiplier = FixidityLib.fixed1(); } /** * @notice Halves the group's slashing multiplier. * @param account The group being slashed. */ function halveSlashingMultiplier(address account) external nonReentrant onlySlasher { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; group.slashInfo.multiplier = FixidityLib.wrap(group.slashInfo.multiplier.unwrap().div(2)); group.slashInfo.lastSlashed = now; } /** * @notice Getter for a group's slashing multiplier. * @param account The group to fetch slashing multiplier for. */ function getValidatorGroupSlashingMultiplier(address account) external view returns (uint256) { require(isValidatorGroup(account), "Not a validator group"); ValidatorGroup storage group = groups[account]; return group.slashInfo.multiplier.unwrap(); } /** * @notice Returns the group that `account` was a member of during `epochNumber`. * @param account The account whose group membership should be returned. * @param epochNumber The epoch number we are querying this account's membership at. * @param index The index into the validator's history struct for their history at `epochNumber`. * @return The group that `account` was a member of during `epochNumber`. */ function groupMembershipInEpoch(address account, uint256 epochNumber, uint256 index) external view returns (address) { require(isValidator(account), "Not a validator"); require(epochNumber <= getEpochNumber(), "Epoch cannot be larger than current"); MembershipHistory storage history = validators[account].membershipHistory; require(index < history.tail.add(history.numEntries), "index out of bounds"); require(index >= history.tail && history.numEntries > 0, "index out of bounds"); bool isExactMatch = history.entries[index].epochNumber == epochNumber; bool isLastEntry = index.sub(history.tail) == history.numEntries.sub(1); bool isWithinRange = history.entries[index].epochNumber < epochNumber && (history.entries[index.add(1)].epochNumber > epochNumber || isLastEntry); require( isExactMatch || isWithinRange, "provided index does not match provided epochNumber at index in history." ); return history.entries[index].group; } }
Updates the group membership history of a particular account. account The account whose group membership has changed. group The group that the account is now a member of. return True upon success. Note that this is used to determine a validator's membership at the time of an election, and so group changes within an epoch will overwrite eachother./ There have been no elections since the validator last changed membership, overwrite the previous entry. Not enough entries, don't remove any. Exactly enough entries, delete the oldest one to account for the one we added. Too many entries, delete the oldest two to account for the one we added.
function updateMembershipHistory(address account, address group) private returns (bool) { MembershipHistory storage history = validators[account].membershipHistory; uint256 epochNumber = getEpochNumber(); uint256 head = history.numEntries == 0 ? 0 : history.tail.add(history.numEntries.sub(1)); if (history.numEntries > 0 && group == address(0)) { history.lastRemovedFromGroupTimestamp = now; } if (history.numEntries > 0 && history.entries[head].epochNumber == epochNumber) { history.entries[head] = MembershipHistoryEntry(epochNumber, group); return true; } history.entries[index] = MembershipHistoryEntry(epochNumber, group); if (history.numEntries < membershipHistoryLength) { history.numEntries = history.numEntries.add(1); delete history.entries[history.tail]; history.tail = history.tail.add(1); delete history.entries[history.tail]; delete history.entries[history.tail.add(1)]; history.numEntries = history.numEntries.sub(1); history.tail = history.tail.add(2); } return true; }
905,935
/** * The edgeless casino contract v2 holds the players&#39;s funds and provides state channel functionality. * The casino has at no time control over the players&#39;s funds. * State channels can be updated and closed from both parties: the player and the casino. * author: Julia Altenried **/ pragma solidity ^0.4.19; contract SafeMath { function safeSub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function safeSub(int a, int b) pure internal returns(int) { if(b < 0) assert(a - b > a); else assert(a - b <= a); return a - b; } function safeAdd(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } function safeMul(uint a, uint b) pure internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } } contract Token { function transferFrom(address sender, address receiver, uint amount) public returns(bool success) {} function transfer(address receiver, uint amount) public returns(bool success) {} function balanceOf(address holder) public constant returns(uint) {} } contract owned { address public owner; modifier onlyOwner { require(msg.sender == owner); _; } function owned() public{ owner = msg.sender; } } /** owner should be able to close the contract is nobody has been using it for at least 30 days */ contract mortal is owned { /** contract can be closed by the owner anytime after this timestamp if non-zero */ uint public closeAt; /** the edgeless token contract */ Token edg; function mortal(address tokenContract) internal{ edg = Token(tokenContract); } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days */ function closeContract(uint playerBalance) internal{ if(closeAt == 0) closeAt = now + 30 days; if(closeAt < now || playerBalance == 0){ edg.transfer(owner, edg.balanceOf(address(this))); selfdestruct(owner); } } /** * in case close has been called accidentally. **/ function open() onlyOwner public{ closeAt = 0; } /** * make sure the contract is not in process of being closed. **/ modifier isAlive { require(closeAt == 0); _; } /** * delays the time of closing. **/ modifier keepAlive { if(closeAt > 0) closeAt = now + 30 days; _; } } contract requiringAuthorization is mortal { /** indicates if an address is authorized to act in the casino&#39;s name */ mapping(address => bool) public authorized; /** tells if an address is allowed to receive funds from the bankroll **/ mapping(address => bool) public allowedReceiver; modifier onlyAuthorized { require(authorized[msg.sender]); _; } /** * Constructor. Authorize the owner. * */ function requiringAuthorization() internal { authorized[msg.sender] = true; allowedReceiver[msg.sender] = true; } /** * authorize a address to call game functions and set configs. * @param addr the address to be authorized **/ function authorize(address addr) public onlyOwner { authorized[addr] = true; } /** * deauthorize a address to call game functions and set configs. * @param addr the address to be deauthorized **/ function deauthorize(address addr) public onlyOwner { authorized[addr] = false; } /** * allow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function allowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = true; } /** * disallow authorized wallets to withdraw funds from the bonkroll to this address * @param receiver the receiver&#39;s address * */ function disallowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = false; } /** * changes the owner of the contract. revokes authorization of the old owner and authorizes the new one. * @param newOwner the address of the new owner * */ function changeOwner(address newOwner) public onlyOwner { deauthorize(owner); authorize(newOwner); disallowReceiver(owner); allowReceiver(newOwner); owner = newOwner; } } contract chargingGas is requiringAuthorization, SafeMath { /** 1 EDG has 5 decimals **/ uint public constant oneEDG = 100000; /** the price per kgas and GWei in tokens (with decimals) */ uint public gasPrice; /** the amount of gas used per transaction in kGas */ mapping(bytes4 => uint) public gasPerTx; /** the number of tokens (5 decimals) payed by the users to cover the gas cost */ uint public gasPayback; function chargingGas(uint kGasPrice) internal{ //deposit, withdrawFor, updateChannel, updateBatch, transferToNewContract bytes4[5] memory signatures = [bytes4(0x3edd1128),0x9607610a, 0xde48ff52, 0xc97b6d1f, 0x6bf06fde]; //amount of gas consumed by the above methods in GWei uint[5] memory gasUsage = [uint(146), 100, 65, 50, 85]; setGasUsage(signatures, gasUsage); setGasPrice(kGasPrice); } /** * sets the amount of gas consumed by methods with the given sigantures. * only called from the edgeless casino constructor. * @param signatures an array of method-signatures * gasNeeded the amount of gas consumed by these methods * */ function setGasUsage(bytes4[5] signatures, uint[5] gasNeeded) public onlyOwner { require(signatures.length == gasNeeded.length); for (uint8 i = 0; i < signatures.length; i++) gasPerTx[signatures[i]] = gasNeeded[i]; } /** * updates the price per 1000 gas in EDG. * @param price the new gas price (with decimals, max 0.1 EDG) **/ function setGasPrice(uint price) public onlyAuthorized { require(price < oneEDG/10); gasPrice = price; } /** * returns the gas cost of the called function. * */ function getGasCost() internal view returns(uint) { return safeMul(safeMul(gasPerTx[msg.sig], gasPrice), tx.gasprice) / 1000000000; } } contract CasinoBank is chargingGas { /** the total balance of all players with virtual decimals **/ uint public playerBalance; /** the balance per player in edgeless tokens with virtual decimals */ mapping(address => uint) public balanceOf; /** in case the user wants/needs to call the withdraw function from his own wallet, he first needs to request a withdrawal */ mapping(address => uint) public withdrawAfter; /** a number to count withdrawal signatures to ensure each signature is different even if withdrawing the same amount to the same address */ mapping(address => uint) public withdrawCount; /** the maximum amount of tokens the user is allowed to deposit (with decimals) */ uint public maxDeposit; /** the maximum withdrawal of tokens the user is allowed to withdraw on one day (only enforced when the tx is not sent from an authorized wallet) **/ uint public maxWithdrawal; /** waiting time for withdrawal if not requested via the server **/ uint public waitingTime; /** the address of the predecessor **/ address public predecessor; /** informs listeners how many tokens were deposited for a player */ event Deposit(address _player, uint _numTokens, uint _gasCost); /** informs listeners how many tokens were withdrawn from the player to the receiver address */ event Withdrawal(address _player, address _receiver, uint _numTokens, uint _gasCost); /** * Constructor. * @param depositLimit the maximum deposit allowed * predecessorAddr the address of the predecessing contract * */ function CasinoBank(uint depositLimit, address predecessorAddr) internal { maxDeposit = depositLimit * oneEDG; maxWithdrawal = maxDeposit; waitingTime = 24 hours; predecessor = predecessorAddr; } /** * accepts deposits for an arbitrary address. * retrieves tokens from the message sender and adds them to the balance of the specified address. * edgeless tokens do not have any decimals, but are represented on this contract with decimals. * @param receiver address of the receiver * numTokens number of tokens to deposit (0 decimals) * chargeGas indicates if the gas cost is subtracted from the user&#39;s edgeless token balance **/ function deposit(address receiver, uint numTokens, bool chargeGas) public isAlive { require(numTokens > 0); uint value = safeMul(numTokens, oneEDG); uint gasCost; if (chargeGas) { gasCost = getGasCost(); value = safeSub(value, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } uint newBalance = safeAdd(balanceOf[receiver], value); require(newBalance <= maxDeposit); assert(edg.transferFrom(msg.sender, address(this), numTokens)); balanceOf[receiver] = newBalance; playerBalance = safeAdd(playerBalance, value); Deposit(receiver, numTokens, gasCost); } /** * If the user wants/needs to withdraw his funds himself, he needs to request the withdrawal first. * This method sets the earliest possible withdrawal date to &#39;waitingTime from now (default 90m, but up to 24h). * Reason: The user should not be able to withdraw his funds, while the the last game methods have not yet been mined. **/ function requestWithdrawal() public { withdrawAfter[msg.sender] = now + waitingTime; } /** * In case the user requested a withdrawal and changes his mind. * Necessary to be able to continue playing. **/ function cancelWithdrawalRequest() public { withdrawAfter[msg.sender] = 0; } /** * withdraws an amount from the user balance if the waiting time passed since the request. * @param amount the amount of tokens to withdraw **/ function withdraw(uint amount) public keepAlive { require(amount <= maxWithdrawal); require(withdrawAfter[msg.sender] > 0 && now > withdrawAfter[msg.sender]); withdrawAfter[msg.sender] = 0; uint value = safeMul(amount, oneEDG); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(msg.sender, amount)); Withdrawal(msg.sender, msg.sender, amount, 0); } /** * lets the owner withdraw from the bankroll * @param receiver the receiver&#39;s address * numTokens the number of tokens to withdraw (0 decimals) **/ function withdrawBankroll(address receiver, uint numTokens) public onlyAuthorized { require(numTokens <= bankroll()); require(allowedReceiver[receiver]); assert(edg.transfer(receiver, numTokens)); } /** * withdraw the gas payback to the owner **/ function withdrawGasPayback() public onlyAuthorized { uint payback = gasPayback / oneEDG; assert(payback > 0); gasPayback = safeSub(gasPayback, payback * oneEDG); assert(edg.transfer(owner, payback)); } /** * returns the current bankroll in tokens with 0 decimals **/ function bankroll() constant public returns(uint) { return safeSub(edg.balanceOf(address(this)), safeAdd(playerBalance, gasPayback) / oneEDG); } /** * updates the maximum deposit. * @param newMax the new maximum deposit (0 decimals) **/ function setMaxDeposit(uint newMax) public onlyAuthorized { maxDeposit = newMax * oneEDG; } /** * updates the maximum withdrawal. * @param newMax the new maximum withdrawal (0 decimals) **/ function setMaxWithdrawal(uint newMax) public onlyAuthorized { maxWithdrawal = newMax * oneEDG; } /** * sets the time the player has to wait for his funds to be unlocked before withdrawal (if not withdrawing with help of the casino server). * the time may not be longer than 24 hours. * @param newWaitingTime the new waiting time in seconds * */ function setWaitingTime(uint newWaitingTime) public onlyAuthorized { require(newWaitingTime <= 24 hours); waitingTime = newWaitingTime; } /** * transfers an amount from the contract balance to the owner&#39;s wallet. * @param receiver the receiver address * amount the amount of tokens to withdraw (0 decimals) * v,r,s the signature of the player **/ function withdrawFor(address receiver, uint amount, uint8 v, bytes32 r, bytes32 s) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(receiver, amount, withdrawCount[receiver]), v, r, s); withdrawCount[receiver]++; uint gasCost = getGasCost(); uint value = safeAdd(safeMul(amount, oneEDG), gasCost); gasPayback = safeAdd(gasPayback, gasCost); balanceOf[player] = safeSub(balanceOf[player], value); playerBalance = safeSub(playerBalance, value); assert(edg.transfer(receiver, amount)); Withdrawal(player, receiver, amount, gasCost); } /** * transfers the player&#39;s tokens directly to the new casino contract after an update. * @param newCasino the address of the new casino contract * v, r, s the signature of the player * chargeGas indicates if the gas cost is payed by the player. * */ function transferToNewContract(address newCasino, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public onlyAuthorized keepAlive { address player = ecrecover(keccak256(address(this), newCasino), v, r, s); uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); uint value = safeSub(balanceOf[player], gasCost); require(value > oneEDG); //fractions of one EDG cannot be withdrawn value /= oneEDG; playerBalance = safeSub(playerBalance, balanceOf[player]); balanceOf[player] = 0; assert(edg.transfer(newCasino, value)); Withdrawal(player, newCasino, value, gasCost); CasinoBank cb = CasinoBank(newCasino); assert(cb.credit(player, value)); } /** * receive a player balance from the predecessor contract. * @param player the address of the player to credit the value for * value the number of tokens to credit (0 decimals) * */ function credit(address player, uint value) public returns(bool) { require(msg.sender == predecessor); uint valueWithDecimals = safeMul(value, oneEDG); balanceOf[player] = safeAdd(balanceOf[player], valueWithDecimals); playerBalance = safeAdd(playerBalance, valueWithDecimals); Deposit(player, value, 0); return true; } /** * lets the owner close the contract if there are no player funds on it or if nobody has been using it for at least 30 days * */ function close() public onlyOwner { closeContract(playerBalance); } } contract EdgelessCasino is CasinoBank{ /** the most recent known state of a state channel */ mapping(address => State) public lastState; /** fired when the state is updated */ event StateUpdate(address player, uint128 count, int128 winBalance, int difference, uint gasCost); /** fired if one of the parties chooses to log the seeds and results */ event GameData(address player, bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint gasCost); struct State{ uint128 count; int128 winBalance; } /** * creates a new edgeless casino contract. * @param predecessorAddress the address of the predecessing contract * tokenContract the address of the Edgeless token contract * depositLimit the maximum deposit allowed * kGasPrice the price per kGas in WEI **/ function EdgelessCasino(address predecessorAddress, address tokenContract, uint depositLimit, uint kGasPrice) CasinoBank(depositLimit, predecessorAddress) mortal(tokenContract) chargingGas(kGasPrice) public{ } /** * updates several state channels at once. can be called by authorized wallets only. * 1. determines the player address from the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalances array of the current wins or losses * gameCounts array of the numbers of signed game moves * v,r,s array of the players&#39;s signatures * chargeGas indicates if the gas costs should be subtracted from the players&#39;s balances * */ function updateBatch(int128[] winBalances, uint128[] gameCounts, uint8[] v, bytes32[] r, bytes32[] s, bool chargeGas) public onlyAuthorized{ require(winBalances.length == gameCounts.length); require(winBalances.length == v.length); require(winBalances.length == r.length); require(winBalances.length == s.length); require(winBalances.length <= 50); address player; uint gasCost = 0; if(chargeGas) gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, safeMul(gasCost, winBalances.length)); for(uint8 i = 0; i < winBalances.length; i++){ player = ecrecover(keccak256(winBalances[i], gameCounts[i]), v[i], r[i], s[i]); _updateState(player, winBalances[i], gameCounts[i], gasCost); } } /** * updates a state channel. can be called by both parties. * 1. verifies the signature. * 2. verifies if the signed game-count is higher than the last known game-count of this channel. * 3. updates the balances accordingly. This means: It checks the already performed updates for this channel and computes * the new balance difference to add or subtract from the player‘s balance. * @param winBalance the current win or loss * gameCount the number of signed game moves * v,r,s the signature of either the casino or the player * chargeGas indicates if the gas costs should be subtracted from the player&#39;s balance * */ function updateState(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s, bool chargeGas) public{ address player = determinePlayer(winBalance, gameCount, v, r, s); uint gasCost = 0; if(player == msg.sender)//if the player closes the state channel himself, make sure the signer is a casino wallet require(authorized[ecrecover(keccak256(player, winBalance, gameCount), v, r, s)]); else if (chargeGas){//subtract the gas costs from the player balance only if the casino wallet is the sender gasCost = getGasCost(); gasPayback = safeAdd(gasPayback, gasCost); } _updateState(player, winBalance, gameCount, gasCost); } /** * internal method to perform the actual state update. * @param player the player address * winBalance the player&#39;s win balance * gameCount the player&#39;s game count * */ function _updateState(address player, int128 winBalance, uint128 gameCount, uint gasCost) internal { State storage last = lastState[player]; require(gameCount > last.count); int difference = updatePlayerBalance(player, winBalance, last.winBalance, gasCost); lastState[player] = State(gameCount, winBalance); StateUpdate(player, gameCount, winBalance, difference, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param winBalance the current winBalance, used to calculate the msg hash * gameCount the current gameCount, used to calculate the msg.hash * v, r, s the signature of the non-sending party * */ function determinePlayer(int128 winBalance, uint128 gameCount, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ if (authorized[msg.sender])//casino is the sender -> player is the signer return ecrecover(keccak256(winBalance, gameCount), v, r, s); else return msg.sender; } /** * computes the difference of the win balance relative to the last known state and adds it to the player&#39;s balance. * in case the casino is the sender, the gas cost in EDG gets subtracted from the player&#39;s balance. * @param player the address of the player * winBalance the current win-balance * lastWinBalance the win-balance of the last known state * gasCost the gas cost of the tx * */ function updatePlayerBalance(address player, int128 winBalance, int128 lastWinBalance, uint gasCost) internal returns(int difference){ difference = safeSub(winBalance, lastWinBalance); int outstanding = safeSub(difference, int(gasCost)); uint outs; if(outstanding < 0){ outs = uint256(outstanding * (-1)); playerBalance = safeSub(playerBalance, outs); balanceOf[player] = safeSub(balanceOf[player], outs); } else{ outs = uint256(outstanding); assert(bankroll() * oneEDG > outs); playerBalance = safeAdd(playerBalance, outs); balanceOf[player] = safeAdd(balanceOf[player], outs); } } /** * logs some seeds and game results for players wishing to have their game history logged by the contract * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party (to make sure the correct results are logged) * */ function logGameData(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) public{ address player = determinePlayer(serverSeeds, clientSeeds, results, v, r, s); uint gasCost; //charge gas in case the server is logging the results for the player if(player != msg.sender){ gasCost = (57 + 768 * serverSeeds.length / 1000)*gasPrice; balanceOf[player] = safeSub(balanceOf[player], gasCost); playerBalance = safeSub(playerBalance, gasCost); gasPayback = safeAdd(gasPayback, gasCost); } GameData(player, serverSeeds, clientSeeds, results, gasCost); } /** * determines if the msg.sender or the signer of the passed signature is the player. returns the player&#39;s address * @param serverSeeds array containing the server seeds * clientSeeds array containing the client seeds * results array containing the results * v, r, s the signature of the non-sending party * */ function determinePlayer(bytes32[] serverSeeds, bytes32[] clientSeeds, int[] results, uint8 v, bytes32 r, bytes32 s) constant internal returns(address){ address signer = ecrecover(keccak256(serverSeeds, clientSeeds, results), v, r, s); if (authorized[msg.sender])//casino is the sender -> player is the signer return signer; else if (authorized[signer]) return msg.sender; else revert(); } }
allow authorized wallets to withdraw funds from the bonkroll to this address receiver the receiver&39;s address /
function allowReceiver(address receiver) public onlyOwner { allowedReceiver[receiver] = true; }
2,416,639
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; /** * @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); } interface IPopsicleV3Optimizer { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @return The address of the Uniswap V3 Pool function pool() external view returns (IUniswapV3Pool); /// @notice The lower tick of the range function tickLower() external view returns (int24); /// @notice The upper tick of the range function tickUpper() external view returns (int24); /** * @notice Deposits tokens in proportion to the Optimizer's current ticks. * @param amount0Desired Max amount of token0 to deposit * @param amount1Desired Max amount of token1 to deposit * @param to address that plp should be transfered * @return shares minted * @return amount0 Amount of token0 deposited * @return amount1 Amount of token1 deposited */ function deposit(uint256 amount0Desired, uint256 amount1Desired, address to) external returns (uint256 shares, uint256 amount0,uint256 amount1); /** * @notice Withdraws tokens in proportion to the Optimizer's holdings. * @dev Removes proportional amount of liquidity from Uniswap. * @param shares burned by sender * @return amount0 Amount of token0 sent to recipient * @return amount1 Amount of token1 sent to recipient */ function withdraw(uint256 shares, address to) external returns (uint256 amount0, uint256 amount1); /** * @notice Updates Optimizer's positions. * @dev Finds base position and limit position for imbalanced token * mints all amounts to this position(including earned fees) */ function rerange() external; /** * @notice Updates Optimizer's positions. Can only be called by the governance. * @dev Swaps imbalanced token. Finds base position and limit position for imbalanced token if * we don't have balance during swap because of price impact. * mints all amounts to this position(including earned fees) */ function rebalance() external; } interface IOptimizerStrategy { /// @return Maximul PLP value that could be minted function maxTotalSupply() external view returns (uint256); /// @notice Period of time that we observe for price slippage /// @return time in seconds function twapDuration() external view returns (uint32); /// @notice Maximum deviation of time waited avarage price in ticks function maxTwapDeviation() external view returns (int24); /// @notice Tick multuplier for base range calculation function tickRangeMultiplier() external view returns (int24); /// @notice The price impact percentage during swap denominated in hundredths of a bip, i.e. 1e-6 /// @return The max price impact percentage function priceImpactPercentage() external view returns (uint24); } library PositionKey { /// @dev Returns the key of the position in the core library function compute( address owner, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, tickLower, tickUpper)); } } /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } /// @title Liquidity and ticks functions /// @notice Provides functions for computing liquidity and ticks for token amounts and prices library PoolVariables { using LowGasSafeMath for uint256; using LowGasSafeMath for uint128; // Cache struct for calculations struct Info { uint256 amount0Desired; uint256 amount1Desired; uint256 amount0; uint256 amount1; uint128 liquidity; int24 tickLower; int24 tickUpper; } /// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`. /// @param pool Uniswap V3 pool /// @param liquidity The liquidity being valued /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amounts of token0 and token1 that corresponds to liquidity function amountsForLiquidity( IUniswapV3Pool pool, uint128 liquidity, int24 _tickLower, int24 _tickUpper ) internal view returns (uint256, uint256) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getAmountsForLiquidity( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), liquidity ); } /// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`. /// @param pool Uniswap V3 pool /// @param amount0 The amount of token0 /// @param amount1 The amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return The maximum amount of liquidity that can be held amount0 and amount1 function liquidityForAmounts( IUniswapV3Pool pool, uint256 amount0, uint256 amount1, int24 _tickLower, int24 _tickUpper ) internal view returns (uint128) { //Get current price from the pool (uint160 sqrtRatioX96, , , , , , ) = pool.slot0(); return LiquidityAmounts.getLiquidityForAmounts( sqrtRatioX96, TickMath.getSqrtRatioAtTick(_tickLower), TickMath.getSqrtRatioAtTick(_tickUpper), amount0, amount1 ); } /// @dev Amounts of token0 and token1 held in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 The amount of token0 held in position /// @return amount1 The amount of token1 held in position function usersAmounts(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint256 amount0, uint256 amount1) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get Position.Info for specified ticks (uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = pool.positions(positionKey); // Calc amounts of token0 and token1 including fees (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); amount0 = amount0.add(tokensOwed0); amount1 = amount1.add(tokensOwed1); } /// @dev Amount of liquidity in contract position. /// @param pool Uniswap V3 pool /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return liquidity stored in position function positionLiquidity(IUniswapV3Pool pool, int24 _tickLower, int24 _tickUpper) internal view returns (uint128 liquidity) { //Compute position key bytes32 positionKey = PositionKey.compute(address(this), _tickLower, _tickUpper); //Get liquidity stored in position (liquidity, , , , ) = pool.positions(positionKey); } /// @dev Common checks for valid tick inputs. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range function checkRange(int24 tickLower, int24 tickUpper) internal pure { require(tickLower < tickUpper, "TLU"); require(tickLower >= TickMath.MIN_TICK, "TLM"); require(tickUpper <= TickMath.MAX_TICK, "TUM"); } /// @dev Rounds tick down towards negative infinity so that it's a multiple /// of `tickSpacing`. function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; return compressed * tickSpacing; } /// @dev Gets ticks with proportion equivalent to desired amount /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param baseThreshold The range for upper and lower ticks /// @param tickSpacing The pool tick spacing /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function getPositionTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 baseThreshold, int24 tickSpacing) internal view returns(int24 tickLower, int24 tickUpper) { Info memory cache = Info(amount0Desired, amount1Desired, 0, 0, 0, 0, 0); // Get current price and tick from the pool ( uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); //Calc base ticks (cache.tickLower, cache.tickUpper) = baseTicks(currentTick, baseThreshold, tickSpacing); //Calc amounts of token0 and token1 that can be stored in base range (cache.amount0, cache.amount1) = amountsForTicks(pool, cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); //Liquidity that can be stored in base range cache.liquidity = liquidityForAmounts(pool, cache.amount0, cache.amount1, cache.tickLower, cache.tickUpper); //Get imbalanced token bool zeroGreaterOne = amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); //Calc new tick(upper or lower) for imbalanced token if ( zeroGreaterOne) { uint160 nextSqrtPrice0 = SqrtPriceMath.getNextSqrtPriceFromAmount0RoundingUp(sqrtPriceX96, cache.liquidity, cache.amount0Desired, false); cache.tickUpper = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice0), tickSpacing); } else{ uint160 nextSqrtPrice1 = SqrtPriceMath.getNextSqrtPriceFromAmount1RoundingDown(sqrtPriceX96, cache.liquidity, cache.amount1Desired, false); cache.tickLower = PoolVariables.floor(TickMath.getTickAtSqrtRatio(nextSqrtPrice1), tickSpacing); } checkRange(cache.tickLower, cache.tickUpper); tickLower = cache.tickLower; tickUpper = cache.tickUpper; } /// @dev Gets amounts of token0 and token1 that can be stored in range of upper and lower ticks /// @param pool Uniswap V3 pool /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param _tickLower The lower tick of the range /// @param _tickUpper The upper tick of the range /// @return amount0 amounts of token0 that can be stored in range /// @return amount1 amounts of token1 that can be stored in range function amountsForTicks(IUniswapV3Pool pool, uint256 amount0Desired, uint256 amount1Desired, int24 _tickLower, int24 _tickUpper) internal view returns(uint256 amount0, uint256 amount1) { uint128 liquidity = liquidityForAmounts(pool, amount0Desired, amount1Desired, _tickLower, _tickUpper); (amount0, amount1) = amountsForLiquidity(pool, liquidity, _tickLower, _tickUpper); } /// @dev Calc base ticks depending on base threshold and tickspacing function baseTicks(int24 currentTick, int24 baseThreshold, int24 tickSpacing) internal pure returns(int24 tickLower, int24 tickUpper) { int24 tickFloor = floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; } /// @dev Get imbalanced token /// @param amount0Desired The desired amount of token0 /// @param amount1Desired The desired amount of token1 /// @param amount0 Amounts of token0 that can be stored in base range /// @param amount1 Amounts of token1 that can be stored in base range /// @return zeroGreaterOne true if token0 is imbalanced. False if token1 is imbalanced function amountsDirection(uint256 amount0Desired, uint256 amount1Desired, uint256 amount0, uint256 amount1) internal pure returns (bool zeroGreaterOne) { zeroGreaterOne = amount0Desired.sub(amount0).mul(amount1Desired) > amount1Desired.sub(amount1).mul(amount0Desired) ? true : false; } // Check price has not moved a lot recently. This mitigates price // manipulation during rebalance and also prevents placing orders // when it's too volatile. function checkDeviation(IUniswapV3Pool pool, int24 maxTwapDeviation, uint32 twapDuration) internal view { (, int24 currentTick, , , , , ) = pool.slot0(); int24 twap = getTwap(pool, twapDuration); int24 deviation = currentTick > twap ? currentTick - twap : twap - currentTick; require(deviation <= maxTwapDeviation, "PSC"); } /// @dev Fetches time-weighted average price in ticks from Uniswap pool for specified duration function getTwap(IUniswapV3Pool pool, uint32 twapDuration) internal view returns (int24) { uint32 _twapDuration = twapDuration; uint32[] memory secondsAgo = new uint32[](2); secondsAgo[0] = _twapDuration; secondsAgo[1] = 0; (int56[] memory tickCumulatives, ) = pool.observe(secondsAgo); return int24((tickCumulatives[1] - tickCumulatives[0]) / _twapDuration); } } /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); } /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); } /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); } /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); } /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions { } /// @title This library is created to conduct a variety of burn liquidity methods library PoolActions { using PoolVariables for IUniswapV3Pool; using LowGasSafeMath for uint256; using SafeCast for uint256; /** * @notice Withdraws liquidity in share proportion to the Optimizer's totalSupply. * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range * @param totalSupply The amount of total shares in existence * @param share to burn * @param to Recipient of amounts * @return amount0 Amount of token0 withdrawed * @return amount1 Amount of token1 withdrawed */ function burnLiquidityShare( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint256 totalSupply, uint256 share, address to ) internal returns (uint256 amount0, uint256 amount1) { require(totalSupply > 0, "TS"); uint128 liquidityInPool = pool.positionLiquidity(tickLower, tickUpper); uint256 liquidity = uint256(liquidityInPool).mul(share) / totalSupply; if (liquidity > 0) { (amount0, amount1) = pool.burn(tickLower, tickUpper, liquidity.toUint128()); if (amount0 > 0 || amount1 > 0) { // collect liquidity share (amount0, amount1) = pool.collect( to, tickLower, tickUpper, amount0.toUint128(), amount1.toUint128() ); } } } /** * @notice Withdraws all liquidity in a range from Uniswap pool * @param pool Uniswap V3 pool * @param tickLower The lower tick of the range * @param tickUpper The upper tick of the range */ function burnAllLiquidity( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper ) internal { // Burn all liquidity in this range uint128 liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity > 0) { pool.burn(tickLower, tickUpper, liquidity); } // Collect all owed tokens pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); } } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } /** * @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 {LowGasSafeMAth} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using LowGasSafeMath 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 {LowGasSafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } } /// @title Function for getting the current chain ID library ChainId { /// @dev Gets the current chain ID /// @return chainId The current chain ID function get() internal pure returns (uint256 chainId) { assembly { chainId := chainid() } } } /** * @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 Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // 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, "ISS"); require(v == 27 || v == 28, "ISV"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "IS"); return signer; } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = ChainId.get(); _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (ChainId.get() == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, ChainId.get(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using LowGasSafeMath 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_) { _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, "TEA")); 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, "DEB")); 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), "FZA"); require(recipient != address(0), "TZA"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "TEB"); _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), "MZA"); _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), "BZA"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "BEB"); _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), "AFZA"); require(spender != address(0), "ATZA"); _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 { } } /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping (address => Counters.Counter) private _nonces; //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") { } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ED"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "IS"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } /// @notice Returns floor(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, floor(x / y) function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := div(x, y) } } } /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint128 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y, string memory errorMessage) internal pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub128(uint128 x, uint128 y) internal pure returns (uint128 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul128(uint128 x, uint128 y) internal pure returns (uint128 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if sum overflows uint128 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub160(uint160 x, uint160 y) internal pure returns (uint160 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); } } /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } } library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "RC"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; } /// @title PopsicleV3 Optimizer is a yield enchancement v3 contract /// @dev PopsicleV3 Optimizer is a Uniswap V3 yield enchancement contract which acts as /// intermediary between the user who wants to provide liquidity to specific pools /// and earn fees from such actions. The contract ensures that user position is in /// range and earns maximum amount of fees available at current liquidity utilization /// rate. contract PopsicleV3Optimizer is ERC20Permit, ReentrancyGuard, IPopsicleV3Optimizer { using LowGasSafeMath for uint256; using LowGasSafeMath for uint160; using LowGasSafeMath for uint128; using UnsafeMath for uint256; using SafeCast for uint256; using PoolVariables for IUniswapV3Pool; using PoolActions for IUniswapV3Pool; //Any data passed through by the caller via the IUniswapV3PoolActions#mint call struct MintCallbackData { address payer; } //Any data passed through by the caller via the IUniswapV3PoolActions#swap call struct SwapCallbackData { bool zeroForOne; } /// @notice Emitted when user adds liquidity /// @param sender The address that minted the liquidity /// @param share The amount of share of liquidity added by the user to position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Deposit( address indexed sender, uint256 share, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user withdraws liquidity /// @param sender The address that minted the liquidity /// @param shares of liquidity withdrawn by the user from the position /// @param amount0 How much token0 was required for the added liquidity /// @param amount1 How much token1 was required for the added liquidity event Withdraw( address indexed sender, uint256 shares, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees was collected from the pool /// @param feesFromPool0 Total amount of fees collected in terms of token 0 /// @param feesFromPool1 Total amount of fees collected in terms of token 1 /// @param usersFees0 Total amount of fees collected by users in terms of token 0 /// @param usersFees1 Total amount of fees collected by users in terms of token 1 event CollectFees( uint256 feesFromPool0, uint256 feesFromPool1, uint256 usersFees0, uint256 usersFees1 ); /// @notice Emitted when fees was compuonded to the pool /// @param amount0 Total amount of fees compounded in terms of token 0 /// @param amount1 Total amount of fees compounded in terms of token 1 event CompoundFees( uint256 amount0, uint256 amount1 ); /// @notice Emitted when PopsicleV3 Optimizer changes the position in the pool /// @param tickLower Lower price tick of the positon /// @param tickUpper Upper price tick of the position /// @param amount0 Amount of token 0 deposited to the position /// @param amount1 Amount of token 1 deposited to the position event Rerange( int24 tickLower, int24 tickUpper, uint256 amount0, uint256 amount1 ); /// @notice Emitted when user collects his fee share /// @param sender User address /// @param fees0 Exact amount of fees claimed by the users in terms of token 0 /// @param fees1 Exact amount of fees claimed by the users in terms of token 1 event RewardPaid( address indexed sender, uint256 fees0, uint256 fees1 ); /// @notice Shows current Optimizer's balances /// @param totalAmount0 Current token0 Optimizer's balance /// @param totalAmount1 Current token1 Optimizer's balance event Snapshot(uint256 totalAmount0, uint256 totalAmount1); event TransferGovernance(address indexed previousGovernance, address indexed newGovernance); /// @notice Prevents calls from users modifier onlyGovernance { require(msg.sender == governance, "OG"); _; } /// @inheritdoc IPopsicleV3Optimizer address public immutable override token0; /// @inheritdoc IPopsicleV3Optimizer address public immutable override token1; // WETH address address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @inheritdoc IPopsicleV3Optimizer int24 public immutable override tickSpacing; uint constant MULTIPLIER = 1e6; uint24 constant GLOBAL_DIVISIONER = 1e6; // for basis point (0.0001%) //The protocol's fee in hundredths of a bip, i.e. 1e-6 uint24 constant protocolFee = 1e5; mapping (address => bool) private _operatorApproved; // @inheritdoc IPopsicleV3Optimizer IUniswapV3Pool public override pool; // Accrued protocol fees in terms of token0 uint256 public protocolFees0; // Accrued protocol fees in terms of token1 uint256 public protocolFees1; // Total lifetime accrued fees in terms of token0 uint256 public totalFees0; // Total lifetime accrued fees in terms of token1 uint256 public totalFees1; // Address of the Optimizer's owner address public governance; // Pending to claim ownership address address public pendingGovernance; //PopsicleV3 Optimizer settings address address public strategy; // Current tick lower of Optimizer pool position int24 public override tickLower; // Current tick higher of Optimizer pool position int24 public override tickUpper; // Checks if Optimizer is initialized bool public initialized; bool private _paused = false; /** * @dev After deploying, strategy can be set via `setStrategy()` * @param _pool Underlying Uniswap V3 pool with fee = 3000 * @param _strategy Underlying Optimizer Strategy for Optimizer settings */ constructor( address _pool, address _strategy ) ERC20("Popsicle LP V3 USDC/WETH", "PLP") ERC20Permit("Popsicle LP V3 USDC/WETH") { pool = IUniswapV3Pool(_pool); strategy = _strategy; token0 = pool.token0(); token1 = pool.token1(); tickSpacing = pool.tickSpacing(); governance = msg.sender; _operatorApproved[msg.sender] = true; } //initialize strategy function init() external onlyGovernance { require(!initialized, "F"); initialized = true; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); ( , int24 currentTick, , , , , ) = pool.slot0(); int24 tickFloor = PoolVariables.floor(currentTick, tickSpacing); tickLower = tickFloor - baseThreshold; tickUpper = tickFloor + baseThreshold; PoolVariables.checkRange(tickLower, tickUpper); //check ticks also for overflow/underflow } /// @inheritdoc IPopsicleV3Optimizer function deposit( uint256 amount0Desired, uint256 amount1Desired, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 shares, uint256 amount0, uint256 amount1 ) { require(amount0Desired > 0 && amount1Desired > 0, "ANV"); _earnFees(); _compoundFees(); // prevent user drains others uint128 liquidityLast = pool.positionLiquidity(tickLower, tickUpper); // compute the liquidity amount uint128 liquidity = pool.liquidityForAmounts(amount0Desired, amount1Desired, tickLower, tickUpper); (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: msg.sender}))); shares = _calcShare(liquidity*MULTIPLIER, liquidityLast*MULTIPLIER); _mint(to, shares); require(IOptimizerStrategy(strategy).maxTotalSupply() >= totalSupply(), "MTS"); emit Deposit(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function withdraw( uint256 shares, address to ) external override nonReentrant checkDeviation whenNotPaused returns ( uint256 amount0, uint256 amount1 ) { require(shares > 0, "S"); require(to != address(0), "WZA"); _earnFees(); _compoundFees(); (amount0, amount1) = pool.burnLiquidityShare(tickLower, tickUpper, totalSupply(), shares, to); require(amount0 > 0 || amount1 > 0, "EA"); // Burn shares _burn(msg.sender, shares); emit Withdraw(msg.sender, shares, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rerange() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); // Emit snapshot to record balances uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); //Get exact ticks depending on Optimizer's balances (tickLower, tickUpper) = pool.getPositionTicks(balance0, balance1, baseThreshold, tickSpacing); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool (uint256 amount0, uint256 amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, amount0, amount1); } /// @inheritdoc IPopsicleV3Optimizer function rebalance() external override nonReentrant checkDeviation { require(_operatorApproved[msg.sender], "ONA"); _earnFees(); //Burn all liquidity from pool to rerange for Optimizer's balances. pool.burnAllLiquidity(tickLower, tickUpper); //Calc base ticks (uint160 sqrtPriceX96, int24 currentTick, , , , , ) = pool.slot0(); PoolVariables.Info memory cache; int24 baseThreshold = tickSpacing * IOptimizerStrategy(strategy).tickRangeMultiplier(); (cache.tickLower, cache.tickUpper) = PoolVariables.baseTicks(currentTick, baseThreshold, tickSpacing); cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); // Calc liquidity for base ticks cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, cache.tickLower, cache.tickUpper); // Get exact amounts for base ticks (cache.amount0, cache.amount1) = pool.amountsForLiquidity(cache.liquidity, cache.tickLower, cache.tickUpper); // Get imbalanced token bool zeroForOne = PoolVariables.amountsDirection(cache.amount0Desired, cache.amount1Desired, cache.amount0, cache.amount1); // Calculate the amount of imbalanced token that should be swapped. Calculations strive to achieve one to one ratio int256 amountSpecified = zeroForOne ? int256(cache.amount0Desired.sub(cache.amount0).unsafeDiv(2)) : int256(cache.amount1Desired.sub(cache.amount1).unsafeDiv(2)); // always positive. "overflow" safe convertion cuz we are dividing by 2 // Calculate Price limit depending on price impact uint160 exactSqrtPriceImpact = sqrtPriceX96.mul160(IOptimizerStrategy(strategy).priceImpactPercentage() / 2) / GLOBAL_DIVISIONER; uint160 sqrtPriceLimitX96 = zeroForOne ? sqrtPriceX96.sub160(exactSqrtPriceImpact) : sqrtPriceX96.add160(exactSqrtPriceImpact); //Swap imbalanced token as long as we haven't used the entire amountSpecified and haven't reached the price limit pool.swap( address(this), zeroForOne, amountSpecified, sqrtPriceLimitX96, abi.encode(SwapCallbackData({zeroForOne: zeroForOne})) ); (sqrtPriceX96, currentTick, , , , , ) = pool.slot0(); // Emit snapshot to record balances cache.amount0Desired = _balance0(); cache.amount1Desired = _balance1(); emit Snapshot(cache.amount0Desired, cache.amount1Desired); //Get exact ticks depending on Optimizer's new balances (tickLower, tickUpper) = pool.getPositionTicks(cache.amount0Desired, cache.amount1Desired, baseThreshold, tickSpacing); cache.liquidity = pool.liquidityForAmounts(cache.amount0Desired, cache.amount1Desired, tickLower, tickUpper); // Add liquidity to the pool (cache.amount0, cache.amount1) = pool.mint( address(this), tickLower, tickUpper, cache.liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit Rerange(tickLower, tickUpper, cache.amount0, cache.amount1); } // Calcs user share depending on deposited amounts function _calcShare(uint256 liquidity, uint256 liquidityLast) internal view returns ( uint256 shares ) { shares = totalSupply() == 0 ? liquidity : liquidity.mul(totalSupply()).unsafeDiv(liquidityLast); } /// @dev Amount of token0 held as unused balance. function _balance0() internal view returns (uint256) { return IERC20(token0).balanceOf(address(this)).sub(protocolFees0); } /// @dev Amount of token1 held as unused balance. function _balance1() internal view returns (uint256) { return IERC20(token1).balanceOf(address(this)).sub(protocolFees1); } /// @dev collects fees from the pool function _earnFees() internal { uint liquidity = pool.positionLiquidity(tickLower, tickUpper); if (liquidity == 0) return; // we can't poke when liquidity is zero // Do zero-burns to poke the Uniswap pools so earned fees are updated pool.burn(tickLower, tickUpper, 0); (uint256 collect0, uint256 collect1) = pool.collect( address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max ); // Calculate protocol's fees uint256 earnedProtocolFees0 = collect0.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); uint256 earnedProtocolFees1 = collect1.mul(protocolFee).unsafeDiv(GLOBAL_DIVISIONER); protocolFees0 = protocolFees0.add(earnedProtocolFees0); protocolFees1 = protocolFees1.add(earnedProtocolFees1); totalFees0 = totalFees0.add(collect0); totalFees1 = totalFees1.add(collect1); emit CollectFees(collect0, collect1, totalFees0, totalFees1); } function _compoundFees() internal returns (uint256 amount0, uint256 amount1){ uint256 balance0 = _balance0(); uint256 balance1 = _balance1(); emit Snapshot(balance0, balance1); //Get Liquidity for Optimizer's balances uint128 liquidity = pool.liquidityForAmounts(balance0, balance1, tickLower, tickUpper); // Add liquidity to the pool if (liquidity > 0) { (amount0, amount1) = pool.mint( address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({payer: address(this)}))); emit CompoundFees(amount0, amount1); } } /// @notice Returns current Optimizer's position in pool function position() external view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1) { bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper); (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1) = pool.positions(positionKey); } /// @notice Returns current Optimizer's users amounts in pool function usersAmounts() external view returns (uint256 amount0, uint256 amount1) { (amount0, amount1) = pool.usersAmounts(tickLower, tickUpper); } /// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint. /// @dev In the implementation you must pay to the pool for the minted liquidity. /// @param amount0 The amount of token0 due to the pool for the minted liquidity /// @param amount1 The amount of token1 due to the pool for the minted liquidity /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call function uniswapV3MintCallback( uint256 amount0, uint256 amount1, bytes calldata data ) external { require(msg.sender == address(pool), "FP"); MintCallbackData memory decoded = abi.decode(data, (MintCallbackData)); if (amount0 > 0) pay(token0, decoded.payer, msg.sender, amount0); if (amount1 > 0) pay(token1, decoded.payer, msg.sender, amount1); } /// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap. /// @dev In the implementation you must pay to the pool for swap. /// @param amount0 The amount of token0 due to the pool for the swap /// @param amount1 The amount of token1 due to the pool for the swap /// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0, int256 amount1, bytes calldata _data ) external { require(msg.sender == address(pool), "FP"); require(amount0 > 0 || amount1 > 0, "LEZ"); // swaps entirely within 0-liquidity regions are not supported SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData)); bool zeroForOne = data.zeroForOne; if (zeroForOne) pay(token0, address(this), msg.sender, uint256(amount0)); else pay(token1, address(this), msg.sender, uint256(amount1)); } /// @param token The token to pay /// @param payer The entity that must pay /// @param recipient The entity that will receive payment /// @param value The amount to pay function pay( address token, address payer, address recipient, uint256 value ) internal { if (token == weth && address(this).balance >= value) { // pay with WETH9 IWETH9(weth).deposit{value: value}(); // wrap only what is needed to pay IWETH9(weth).transfer(recipient, value); } else if (payer == address(this)) { // pay with tokens already in the contract (for the exact input multihop case) TransferHelper.safeTransfer(token, recipient, value); } else { // pull payment TransferHelper.safeTransferFrom(token, payer, recipient, value); } } /** * @notice Used to withdraw accumulated protocol fees. */ function collectProtocolFees( uint256 amount0, uint256 amount1 ) external nonReentrant onlyGovernance { _earnFees(); require(protocolFees0 >= amount0, "A0F"); require(protocolFees1 >= amount1, "A1F"); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); require(balance0 >= amount0 && balance1 >= amount1); if (amount0 > 0) pay(token0, address(this), msg.sender, amount0); if (amount1 > 0) pay(token1, address(this), msg.sender, amount1); protocolFees0 = protocolFees0.sub(amount0); protocolFees1 = protocolFees1.sub(amount1); _compoundFees(); emit RewardPaid(msg.sender, amount0, amount1); } // Function modifier that checks if price has not moved a lot recently. // This mitigates price manipulation during rebalance and also prevents placing orders // when it's too volatile. modifier checkDeviation() { pool.checkDeviation(IOptimizerStrategy(strategy).maxTwapDeviation(), IOptimizerStrategy(strategy).twapDuration()); _; } /** * @notice `setGovernance()` should be called by the existing governance * address prior to calling this function. */ function setGovernance(address _governance) external onlyGovernance { pendingGovernance = _governance; } /** * @notice Governance address is not updated until the new governance * address has called `acceptGovernance()` to accept this responsibility. */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "PG"); emit TransferGovernance(governance, pendingGovernance); pendingGovernance = address(0); governance = msg.sender; } // Sets new strategy contract address for new settings function setStrategy(address _strategy) external onlyGovernance { require(_strategy != address(0), "NA"); strategy = _strategy; } function approveOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = true; } function disableOperator(address _operator) external onlyGovernance { _operatorApproved[_operator] = false; } function isOperator(address _operator) external view returns (bool) { return _operatorApproved[_operator]; } /** * @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, "P"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "NP"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() external onlyGovernance whenNotPaused { _paused = true; } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function unpause() external onlyGovernance whenPaused { _paused = false; } }
Returns x y, reverts if overflows x The multiplicand y The multiplier return z The product of x and y
function mul160(uint160 x, uint160 y) internal pure returns (uint160 z) { require(x == 0 || (z = x * y) / x == y); }
9,468
./partial_match/1/0x69b4fAac37Df45DC1Ce898f550Fe10E0714f71c1/sources/TEDpresale.sol
function to change the end date of the ICO/
function setEndDate(uint256 daysToEndFromToday) public onlyOwner returns(bool) { daysToEndFromToday = daysToEndFromToday * 1 days; endTime = now + daysToEndFromToday; }
2,628,854
pragma solidity 0.5.0; // Update to Solidity 0.5 contract Merchandise { address owner; bool online; struct Item { uint itemId; address seller; address buyer; string itemName; string itemDesc; uint itemPrice; bool sold; bool shipped; bool received; } Item[] public items; constructor() public { owner = msg.sender; online = true; // addItem("First Item", "Added by Contract deployment", 1 ether); } function kill() public { require(msg.sender == owner, "Only contract owner can kill contract"); selfdestruct(msg.sender); // Can only transfer funds to "address payable" types, so use msg.sender here } function setOnline(bool status) public { require(msg.sender == owner, "Only contract owner can set online status"); online = status; } event AddListing( address seller, string name, uint price ); function addItem(string memory name, string memory description, uint price) public returns(uint) { // string storage ^^ location must now be explicitly declared require(online == true, "Store must be online to add items"); require(price > 0, "Price must be greater than zero"); uint initialLength = items.length; items.push(Item({ itemId: items.length, seller: msg.sender, buyer: address(0), itemName: name, itemDesc: description, itemPrice: price, sold: false, shipped: false, received: false })); emit AddListing(msg.sender, name, price); assert(items.length == initialLength + 1); return items.length; } function getItem(uint itemId) public view returns( uint, string memory, string memory, uint, bool, bool, bool // string storage location ^^ must be explicitly declared ) { return ( items[itemId].itemId, items[itemId].itemName, items[itemId].itemDesc, items[itemId].itemPrice, items[itemId].sold, items[itemId].shipped, items[itemId].received ); } function buyItem(uint itemId) public payable returns(bool) { require(online = true, "Store must be online to buy items"); require(msg.value == items[itemId].itemPrice, "Eth submitted must equal purchase price"); require(items[itemId].sold != true, "Cannot purchase items already sold"); items[itemId].buyer = msg.sender; items[itemId].sold = true; return true; } function shipItem(uint itemId) public { require(items[itemId].sold == true, "Cannot ship unsold items"); items[itemId].shipped = true; } function receiveItem(uint itemId) public { require(items[itemId].shipped == true, "Cannot receive unsold items"); require(msg.sender == items[itemId].buyer, "Only buyer can mark item as received"); items[itemId].received = true; } function claimFunds(uint itemId) public { require(online == true, "Store must be online to claim funds"); require(msg.sender == items[itemId].seller, "Only seller can claim funds"); require(items[itemId].received == true, "Cannot claim funds until item received"); msg.sender.transfer(items[itemId].itemPrice); } }
string storage location ^^ must be explicitly declared
function getItem(uint itemId) public view returns( uint, string memory, string memory, uint, bool, bool, bool ) { return ( items[itemId].itemId, items[itemId].itemName, items[itemId].itemDesc, items[itemId].itemPrice, items[itemId].sold, items[itemId].shipped, items[itemId].received ); }
1,003,683
./partial_match/1/0x3a7055B5B46976b129dCfAB9F73d7fae8ddD54E7/sources/Cramereum.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Cramereum", "CRAMER") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 4; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 4; uint256 _earlySellDevFee = 0 ; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
11,018,908
// SPDX-License-Identifier: GPL-3.0 // Forked from https://github.com/ourzora/core @ 450cd154bfbb70f62e94050cc3f1560d58e0506a pragma solidity >=0.8.4; pragma experimental ABIEncoderV2; import "./ERC721Burnable.sol"; import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import { Counters } from "@openzeppelin/contracts/utils/Counters.sol"; import { SafeMath } from "@openzeppelin/contracts/utils/math/SafeMath.sol"; import { Math } from "@openzeppelin/contracts/utils/math/Math.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import { Decimal } from "./Decimal.sol"; import { IMarket } from "./interfaces/IMarket.sol"; import { IMedia } from "./interfaces/IMedia.sol"; import { IZoo } from "./interfaces/IZoo.sol"; import "./console.sol"; /** * @title A media value system, with perpetual equity to creators * @notice This contract provides an interface to mint media with a market */ contract ZooMedia is IMedia, ERC721Burnable, ReentrancyGuard { using Counters for Counters.Counter; using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; /* ******* * Globals * ******* */ // Deployment Address address private _owner; // Address of ZooKeeper address public keeperAddress; // Address of ZooMarket address public marketAddress; // Mapping from token to previous owner of the token mapping(uint256 => address) public previousTokenOwners; // Mapping from token id to creator address mapping(uint256 => address) public tokenCreators; // Mapping from creator address to their (enumerable) set of created tokens mapping(address => EnumerableSet.UintSet) private _creatorTokens; // Mapping from token id to sha256 hash of content mapping(uint256 => bytes32) public tokenContentHashes; // Mapping from token id to sha256 hash of metadata mapping(uint256 => bytes32) public tokenMetadataHashes; // Mapping from token id to metadataURI mapping(uint256 => string) private _tokenMetadataURIs; // Mapping from contentHash to bool mapping(bytes32 => bool) private _contentHashes; //keccak256("Permit(address spender,uint256 tokenID,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad; //keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)"); bytes32 public constant MINT_WITH_SIG_TYPEHASH = 0x2952e482b8e2b192305f87374d7af45dc2eafafe4f50d26a0c02e90f2fdbe14b; // Mapping from address to token id to permit nonce mapping(address => mapping(uint256 => uint256)) public permitNonces; // Mapping from address to mint with sig nonce mapping(address => uint256) public mintWithSigNonces; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * bytes4(keccak256('tokenMetadataURI(uint256)')) == 0x157c3df9 * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd ^ 0x157c3df9 == 0x4e222e66 */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x4e222e66; Counters.Counter private _tokenIDTracker; /* ********* * Modifiers * ********* */ modifier onlyZoo() { require( keeperAddress == msg.sender || marketAddress == msg.sender, "ZooMarket: Only Zoo contracts can call this method" ); _; } modifier onlyOwner() { require(_owner == msg.sender, "ZooMarket: Only owner has access"); _; } /** * @notice Require that the token has not been burned and has been minted */ modifier onlyExistingToken(uint256 tokenID) { require(tokenExists(tokenID), "ZooMedia: nonexistent token"); _; } /** * @notice Require that the token has had a content hash set */ modifier onlyTokenWithContentHash(uint256 tokenID) { require( tokenContentHashes[tokenID] != 0, "ZooMedia: token does not have hash of created content" ); _; } /** * @notice Require that the token has had a metadata hash set */ modifier onlyTokenWithMetadataHash(uint256 tokenID) { require( tokenMetadataHashes[tokenID] != 0, "ZooMedia: token does not have hash of its metadata" ); _; } /** * @notice Ensure that the provided spender is the approved or the owner of * the media for the specified tokenID */ modifier onlyApprovedOrOwner(address spender, uint256 tokenID) { require( _isKeeper(msg.sender) || _isApprovedOrOwner(spender, tokenID), "ZooMedia: Only approved or owner" ); _; } /** * @notice Ensure the token has been created (even if it has been burned) */ modifier onlyTokenCreated(uint256 tokenID) { require( _tokenIDTracker.current() >= tokenID, "ZooMedia: token with that id does not exist" ); _; } /** * @notice Ensure that the provided URI is not empty */ modifier onlyValidURI(string memory uri) { require( bytes(uri).length != 0, "ZooMedia: specified uri must be non-empty" ); _; } /** * @notice On deployment, set the market contract address and register the * ERC721 metadata interface */ constructor( string memory name, string memory symbol ) ERC721(name, symbol) { _owner = msg.sender; _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function _isKeeper(address _address) internal view returns (bool) { return keeperAddress == _address; } /** * @notice Sets the media contract address. This address is the only permitted address that * can call the mutable functions. This method can only be called once. */ function configure(address _keeperAddress, address _marketAddress) external onlyOwner { // require(marketAddress == address(0), "ZooMedia: Already configured"); // require(keeperAddress == address(0), "ZooMedia: Already configured"); require( _keeperAddress != address(0), "Market: cannot set keeper contract as zero address" ); require( _marketAddress != address(0), "Market: cannot set market contract as zero address" ); keeperAddress = _keeperAddress; marketAddress = _marketAddress; } /* ************** * View Functions * ************** */ /** * @notice Helper to check that token has not been burned or minted */ function tokenExists(uint256 tokenID) public override view returns (bool) { return _exists(tokenID); } /** * @notice return the URI for a particular piece of media with the specified tokenID * @dev This function is an override of the base OZ implementation because we * will return the tokenURI even if the media has been burned. In addition, this * protocol does not support a base URI, so relevant conditionals are removed. * @return the URI for a token */ function tokenURI(uint256 tokenID) public view override onlyTokenCreated(tokenID) returns (string memory) { string memory _tokenURI = _tokenURIs[tokenID]; return _tokenURI; } /** * @notice Return the metadata URI for a piece of media given the token URI * @return the metadata URI for the token */ function tokenMetadataURI(uint256 tokenID) external view override onlyTokenCreated(tokenID) returns (string memory) { return _tokenMetadataURIs[tokenID]; } /* **************** * Public Functions * **************** */ /** * @notice see IMedia */ function mint(MediaData memory data, IMarket.BidShares memory bidShares) public override nonReentrant { _mintForCreator(msg.sender, data, bidShares, ""); } function _hashToken(address owner, IZoo.Token memory token) private view returns (IZoo.Token memory) { console.log('_hashToken', token.data.tokenURI, token.data.metadataURI); token.data.contentHash = keccak256( abi.encodePacked(token.data.tokenURI, block.number, owner) ); token.data.metadataHash = keccak256( abi.encodePacked(token.data.metadataURI, block.number, owner) ); return token; } function mintToken(address owner, IZoo.Token memory token) external override nonReentrant returns (IZoo.Token memory) { console.log('mintToken', owner, token.name); token = _hashToken(owner, token); _mintForCreator(owner, token.data, token.bidShares, ""); uint256 id = getRecentToken(owner); token.id = id; return token; } function burnToken(address owner, uint256 tokenID) external override nonReentrant onlyExistingToken(tokenID) onlyApprovedOrOwner(owner, tokenID) { _burn(tokenID); } /** * @notice see IMedia */ function mintWithSig( address creator, MediaData memory data, IMarket.BidShares memory bidShares, EIP712Signature memory sig ) public override nonReentrant { require( sig.deadline == 0 || sig.deadline >= block.timestamp, "ZooMedia: mintWithSig expired" ); bytes32 domainSeparator = _calculateDomainSeparator(); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode( MINT_WITH_SIG_TYPEHASH, data.contentHash, data.metadataHash, bidShares.creator.value, mintWithSigNonces[creator]++, sig.deadline ) ) ) ); address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && creator == recoveredAddress, "ZooMedia: Signature invalid" ); _mintForCreator(recoveredAddress, data, bidShares, ""); } /** * @notice see IMedia */ function transfer(uint256 tokenID, address recipient) external { require(msg.sender == marketAddress, "ZooMedia: only market contract"); previousTokenOwners[tokenID] = ownerOf(tokenID); _transfer(ownerOf(tokenID), recipient, tokenID); } /** * @notice see IMedia */ function getRecentToken(address creator) public view returns (uint256) { uint256 length = EnumerableSet.length(_creatorTokens[creator]) - 1; return EnumerableSet.at(_creatorTokens[creator], length); } /** * @notice see IMedia */ function auctionTransfer(uint256 tokenID, address recipient) external override { require(msg.sender == marketAddress, "ZooMedia: only market contract"); previousTokenOwners[tokenID] = ownerOf(tokenID); _safeTransfer(ownerOf(tokenID), recipient, tokenID, ""); } /** * @notice see IMedia */ function setAsk(uint256 tokenID, IMarket.Ask memory ask) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenID) { IMarket(marketAddress).setAsk(tokenID, ask); } /** * @notice see IMedia */ function removeAsk(uint256 tokenID) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenID) { IMarket(marketAddress).removeAsk(tokenID); } /** * @notice see IMedia */ function setBid(uint256 tokenID, IMarket.Bid memory bid) public override nonReentrant onlyExistingToken(tokenID) { require(msg.sender == bid.bidder, "Market: Bidder must be msg sender"); IMarket(marketAddress).setBid(tokenID, bid, msg.sender); } /** * @notice see IMedia */ function removeBid(uint256 tokenID) external override nonReentrant onlyTokenCreated(tokenID) { IMarket(marketAddress).removeBid(tokenID, msg.sender); } /** * @notice see IMedia */ function acceptBid(uint256 tokenID, IMarket.Bid memory bid) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenID) { IMarket(marketAddress).acceptBid(tokenID, bid); } /** * @notice Burn a token. * @dev Only callable if the media owner is also the creator. */ function burn(uint256 tokenID) public override nonReentrant onlyExistingToken(tokenID) onlyApprovedOrOwner(msg.sender, tokenID) { address owner = ownerOf(tokenID); require( tokenCreators[tokenID] == owner, "ZooMedia: owner is not creator of media" ); _burn(tokenID); } /** * @notice Revoke the approvals for a token. The provided `approve` function is not sufficient * for this protocol, as it does not allow an approved address to revoke it's own approval. * In instances where a 3rd party is interacting on a user's behalf via `permit`, they should * revoke their approval once their task is complete as a best practice. */ function revokeApproval(uint256 tokenID) external override nonReentrant { require( msg.sender == getApproved(tokenID), "ZooMedia: caller not approved address" ); _approve(address(0), tokenID); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenURI(uint256 tokenID, string calldata _tokenURI) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenID) onlyTokenWithContentHash(tokenID) onlyValidURI(_tokenURI) { _setTokenURI(tokenID, _tokenURI); emit TokenURIUpdated(tokenID, msg.sender, _tokenURI); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenMetadataURI( uint256 tokenID, string calldata metadataURI ) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenID) onlyTokenWithMetadataHash(tokenID) onlyValidURI(metadataURI) { _setTokenMetadataURI(tokenID, metadataURI); emit TokenMetadataURIUpdated(tokenID, msg.sender, metadataURI); } /** * @notice See IMedia * @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified * for ERC-721. */ function permit( address spender, uint256 tokenID, EIP712Signature memory sig ) public override nonReentrant onlyExistingToken(tokenID) { require( sig.deadline == 0 || sig.deadline >= block.timestamp, "ZooMedia: Permit expired" ); require(spender != address(0), "ZooMedia: spender cannot be 0x0"); bytes32 domainSeparator = _calculateDomainSeparator(); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, keccak256( abi.encode( PERMIT_TYPEHASH, spender, tokenID, permitNonces[ownerOf(tokenID)][tokenID]++, sig.deadline ) ) ) ); address recoveredAddress = ecrecover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && ownerOf(tokenID) == recoveredAddress, "ZooMedia: Signature invalid" ); _approve(spender, tokenID); } /* ***************** * Private Functions * ***************** */ /** * @notice Creates a new token for `creator`. 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-_safeMint}. * * On mint, also set the sha256 hashes of the content and its metadata for integrity * checks, along with the initial URIs to point to the content and metadata. Attribute * the token ID to the creator, mark the content hash as used, and set the bid shares for * the media's market. * * Note that although the content hash must be unique for future mints to prevent duplicate media, * metadata has no such requirement. */ function _mintForCreator( address creator, MediaData memory data, IMarket.BidShares memory bidShares, bytes memory tokenType ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) { console.log("_mintForCreator", data.tokenURI, data.metadataURI, bidShares.creator.value); require( data.contentHash != 0, "ZooMedia: content hash must be non-zero" ); require( _contentHashes[data.contentHash] == false, "ZooMedia: a token has already been created with this content hash" ); require( data.metadataHash != 0, "ZooMedia: metadata hash must be non-zero" ); // Get a new ID _tokenIDTracker.increment(); uint256 tokenID = _tokenIDTracker.current(); console.log("_safeMint", creator, tokenID); _safeMint(creator, tokenID, tokenType); _setTokenContentHash(tokenID, data.contentHash); _setTokenMetadataHash(tokenID, data.metadataHash); _setTokenMetadataURI(tokenID, data.metadataURI); _setTokenURI(tokenID, data.tokenURI); _creatorTokens[creator].add(tokenID); _contentHashes[data.contentHash] = true; tokenCreators[tokenID] = creator; previousTokenOwners[tokenID] = creator; console.log("_creatorTokens[creator].add(tokenID)", creator, tokenID); // ZK now responsible for setting bid shares externally // IMarket(marketAddress).setBidShares(tokenID, bidShares); } function _setTokenContentHash(uint256 tokenID, bytes32 contentHash) internal virtual onlyExistingToken(tokenID) { tokenContentHashes[tokenID] = contentHash; } function _setTokenMetadataHash(uint256 tokenID, bytes32 metadataHash) internal virtual onlyExistingToken(tokenID) { tokenMetadataHashes[tokenID] = metadataHash; } function _setTokenMetadataURI(uint256 tokenID, string memory metadataURI) internal virtual onlyExistingToken(tokenID) { _tokenMetadataURIs[tokenID] = metadataURI; } /** * @notice Destroys `tokenID`. * @dev We modify the OZ _burn implementation to * maintain metadata and to remove the * previous token owner from the piece */ function _burn(uint256 tokenID) internal override { // string memory _tokenURI = _tokenURIs[tokenID]; super._burn(tokenID); // if (bytes(_tokenURI).length != 0) { // _tokenURIs[tokenID] = _tokenURI; // } delete previousTokenOwners[tokenID]; } /** * @notice transfer a token and remove the ask for it. */ function _transfer( address from, address to, uint256 tokenID ) internal override { IMarket(marketAddress).removeAsk(tokenID); super._transfer(from, to, tokenID); } /** * @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _calculateDomainSeparator() internal view returns (bytes32) { uint256 chainID; /* solium-disable-next-line */ assembly { chainID := chainid() } return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainID,address verifyingContract)" ), keccak256(bytes("CryptoZoo")), keccak256(bytes("1")), chainID, address(this) ) ); } }
Return the metadata URI for a piece of media given the token URI return the metadata URI for the token/
function tokenMetadataURI(uint256 tokenID) external view override onlyTokenCreated(tokenID) returns (string memory) { return _tokenMetadataURIs[tokenID]; }
12,704,594
pragma solidity ^0.4.11; import "./token/StandardToken.sol"; import "./ownership/Ownable.sol"; contract ENSBidToken is StandardToken, Ownable { // [x] 實作 ERC20 // [x] 股權形式分配的 Token 模式 // [x] 開發團隊的 Token 鎖定一年 // [x] 發售 50%,開發團隊 50% // [x] 分潤模式,提供一個 function 可以將分配利潤發放給 token holder event ShareBenefit(string _tx, address _shareHolder, uint256 _balance, uint256 _shareBenefit); event BenefitReportInfo(uint _year, uint _month, uint256 _benefitInWei); event Finalized(); string public name; // 名稱 string public symbol; // token 代號 uint256 public decimals = 0; // decimals address public contractAddress; // contract address address public ownerWalletAddress; // owner wallet address uint256 public minInvestInWei; // 最低投資金額 in wei uint256 public startBlock; // ICO 起始的 block number uint256 public endBlock; // ICO 結束的 block number uint256 public maxTokenSupply; // ICO 的 max token,透過 USD to ETH 換算出來 uint256 public initializedTime; // 起始時間,合約部署的時候會寫入 uint256 public lockoutTime; // develop team lock time bool public paused; // 暫停合約功能執行 bool public initialized; // 合約啟動 uint256 public finalizedBlock; // 合約終止投資的區塊編號 uint256 public finalizedTime; // 合約終止投資的時間 struct ShareHolder { bool isExists; bool isPayable; uint256 shareBenefitInWei; } struct BenefitReport { uint year; uint month; uint256 benefitInWei; } ShareHolder public shareHolder; BenefitReport public benefitReport; mapping (address => ShareHolder) public shareHolders; address[] public shareHolderArray; // share holder array BenefitReport[] public benefitReportArray; /** * @dev Throws if contract paused. */ modifier notPaused() { require(paused == false); _; } /** * @dev Throws if contract is paused. */ modifier isPaused() { require(paused == true); _; } /** * @dev Throws if contract not initialized. */ modifier isInitialized() { require(initialized == true); _; } /** * @dev Throws if owner token in lockout period. */ modifier notLockout() { require(msg.sender != ownerWalletAddress || now > (finalizedTime + lockoutTime)); _; } /** * @dev Throws if contract not open. */ modifier isContractOpen() { require( getBlockNumber() >= startBlock && getBlockNumber() <= endBlock && finalizedBlock == 0); _; } modifier isFinalized() { require(finalizedBlock > 0 && finalizedTime > 0); _; } /** * @dev Contract constructor. */ function ENSBidToken() { paused = false; } function initialize( string _name, string _symbol, uint256 _decimals, address _contractAddress, address _ownerWalletAddress, uint256 _startBlock, uint256 _endBlock, uint256 _initializedTime, uint256 _lockoutTime, uint256 _minInvestInWei, uint256 _maxTokenSupply) onlyOwner { require(bytes(name).length == 0); require(bytes(symbol).length == 0); require(decimals == 0); require(contractAddress == 0x0); require(ownerWalletAddress == 0x0); require(totalSupply == 0); require(decimals == 0); require(_startBlock >= getBlockNumber()); require(_startBlock < _endBlock); require(initializedTime == 0); require(lockoutTime == 0); require(_maxTokenSupply >= totalSupply); name = _name; symbol = _symbol; decimals = _decimals; contractAddress = _contractAddress; ownerWalletAddress = _ownerWalletAddress; startBlock = _startBlock; endBlock = _endBlock; initializedTime = _initializedTime; lockoutTime = _lockoutTime; minInvestInWei = _minInvestInWei; maxTokenSupply = _maxTokenSupply; initialized = true; } /** * @dev Finalize contract */ function finalize() public isInitialized { require(getBlockNumber() >= startBlock); require(msg.sender == owner || getBlockNumber() > endBlock); finalizedBlock = getBlockNumber(); finalizedTime = now; Finalized(); } /** * @dev fallback function accept ether */ function () payable { proxyPayment(msg.sender); } /** * @dev payment function, transfer eth to token * @param _sender The sender address */ function proxyPayment(address _sender) public payable notPaused isInitialized isContractOpen returns (bool) { require(msg.value > 0); uint256 amount = msg.value; require(amount >= minInvestInWei); uint256 refund = amount % minInvestInWei; // 退款機制 uint256 tokens = (amount - refund) / minInvestInWei; // 透過最小投注金額換算所得的token數量 uint256 totalTokens = tokens * 2; require(totalSupply.add(totalTokens) <= maxTokenSupply); totalSupply = totalSupply.add(totalTokens); balances[_sender] = balances[_sender].add(tokens); // 發送 token 給投資者 balances[owner] = balances[owner].add(tokens); // 發送 token 給開發者 if (shareHolders[msg.sender].isExists != true) { shareHolders[msg.sender].isExists = true; shareHolders[msg.sender].isPayable = true; shareHolderArray.push(msg.sender); } require(ownerWalletAddress.send(amount - refund)); // 扣掉退款金額,將ETH轉到owner錢包中 if (refund > 0) { require(msg.sender.send(refund)); // 傳送退款金額給 msg.sender } return true; } /** * @dev pause contract */ function pauseContract() onlyOwner { paused = true; } /** * @dev resume contract */ function resumeContract() onlyOwner { paused = false; } /** * @dev get block number */ function getBlockNumber() internal constant returns (uint256) { return block.number; } /** * @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) notLockout returns (bool) { 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]; } /** * @dev ERC20 transfer */ function transfer(address _to, uint256 _value) notPaused isFinalized notLockout returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if (shareHolders[_to].isExists != true) { shareHolders[_to].isExists = true; shareHolders[_to].isPayable = true; shareHolderArray.push(_to); } Transfer(msg.sender, _to, _value); return true; } /** * @dev ERC20 transferFrom */ function transferFrom(address _from, address _to, uint256 _value) notPaused isFinalized returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); if (shareHolders[_to].isExists != true) { shareHolders[_to].isExists = true; shareHolders[_to].isPayable = true; shareHolderArray.push(_to); } Transfer(_from, _to, _value); return true; } /** * gas per address: 5560 * @dev share in the benefit * @param _address address of token holders * @param _benefitInWei benefit in wei to token holders */ function shareBenefit(address[] _address, uint256[] _benefitInWei) onlyOwner { require(_address.length > 0); require(_address.length == _benefitInWei.length); uint256 i = 0; while (i < _address.length && msg.gas > 3000000) { address _shareHolder = _address[i]; shareHolders[_shareHolder].shareBenefitInWei += _benefitInWei[i]; i++; } } /** * @dev owner deposit benefit ETH and store in BenefitReport * @param _year year of benefit report * @param _month month of benefit report */ function depositBenefit(uint _year, uint _month) onlyOwner payable { require(msg.value > 0); benefitReportArray.push(BenefitReport(_year, _month, msg.value)); BenefitReportInfo(_year, _month, msg.value); } }
Contract constructor./
function ENSBidToken() { paused = false; }
2,464,480
./full_match/1/0x3c1164531d5857029ae5412E49999306547834d8/sources/@rmrk-team/evm-contracts/contracts/RMRK/equippable/RMRKMinifiedEquippable.sol
Used to check if nesting a given token into a specified token would create an inheritance loop. If a loop would occur, the tokens would be unmanageable, so the execution is reverted if one is detected. The check for inheritance loop is bounded to guard against too much gas being consumed. currentId ID of the token that would be nested targetContract Address of the collection smart contract of the token into which the given token would be nested targetId ID of the token into which the given token would be nested/ If there's a final address, we're good. There's no loop. Ff the current nft is an ancestor at some point, there is an inheritance loop
function _checkForInheritanceLoop( uint256 currentId, address targetContract, uint256 targetId ) private view { for (uint256 i; i < _MAX_LEVELS_TO_CHECK_FOR_INHERITANCE_LOOP; ) { ( address nextOwner, uint256 nextOwnerTokenId, bool isNft ) = IERC6059(targetContract).directOwnerOf(targetId); if (!isNft) { return; } if (nextOwner == address(this) && nextOwnerTokenId == currentId) { revert RMRKNestableTransferToDescendant(); } targetId = nextOwnerTokenId; unchecked { ++i; } } revert RMRKNestableTooDeep(); }
9,657,676
// Copyright (C) 2015 Forecast Foundation OU, full GPL notice in LICENSE // Bid / Ask actions: puts orders on the book // price is denominated by the specific market's numTicks // amount is the number of attoshares the order is for (either to buy or to sell). // price is the exact price you want to buy/sell at [which may not be the cost, for example to short a yesNo market it'll cost numTicks-price, to go long it'll cost price] contract IERC20 { function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IStandardToken { function noHooksTransfer(address recipient, uint256 amount) external returns (bool); } contract ITyped { function getTypeName() public view returns (bytes32); } contract IReputationToken is IERC20 { function migrateOutByPayout(uint256[] memory _payoutNumerators, uint256 _attotokens) public returns (bool); function migrateIn(address _reporter, uint256 _attotokens) public returns (bool); function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getTotalMigrated() public view returns (uint256); function getTotalTheoreticalSupply() public view returns (uint256); function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool); } contract IV2ReputationToken is IReputationToken, IStandardToken { function burnForMarket(uint256 _amountToBurn) public returns (bool); function mintForUniverse(uint256 _amountToMint, address _target) public returns (bool); } contract IOwnable { function getOwner() public view returns (address); function transferOwnership(address _newOwner) public returns (bool); } contract ICash is IERC20 { function joinMint(address usr, uint wad) public returns (bool); function joinBurn(address usr, uint wad) public returns (bool); } contract IShareToken is ITyped, IERC20 { function initialize(IAugur _augur, IMarket _market, uint256 _outcome, address _erc1820RegistryAddress) external; function createShares(address _owner, uint256 _amount) external returns (bool); function destroyShares(address, uint256 balance) external returns (bool); function getMarket() external view returns (IMarket); function getOutcome() external view returns (uint256); function trustedOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedFillOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); function trustedCancelOrderTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool); } contract IReportingParticipant { function getStake() public view returns (uint256); function getPayoutDistributionHash() public view returns (bytes32); function liquidateLosing() public; function redeem(address _redeemer) public returns (bool); function isDisavowed() public view returns (bool); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getMarket() public view returns (IMarket); function getSize() public view returns (uint256); } contract IInitialReporter is IReportingParticipant { function initialize(IAugur _augur, IMarket _market, address _designatedReporter) public; function report(address _reporter, bytes32 _payoutDistributionHash, uint256[] memory _payoutNumerators, uint256 _initialReportStake) public; function designatedReporterShowed() public view returns (bool); function designatedReporterWasCorrect() public view returns (bool); function getDesignatedReporter() public view returns (address); function getReportTimestamp() public view returns (uint256); function migrateToNewUniverse(address _designatedReporter) public; function returnRepFromDisavow() public; } contract IMarket is IOwnable { enum MarketType { YES_NO, CATEGORICAL, SCALAR } function initialize(IAugur _augur, IUniverse _universe, uint256 _endTime, uint256 _feePerCashInAttoCash, uint256 _affiliateFeeDivisor, address _designatedReporterAddress, address _creator, uint256 _numOutcomes, uint256 _numTicks) public; function derivePayoutDistributionHash(uint256[] memory _payoutNumerators) public view returns (bytes32); function getUniverse() public view returns (IUniverse); function getDisputeWindow() public view returns (IDisputeWindow); function getNumberOfOutcomes() public view returns (uint256); function getNumTicks() public view returns (uint256); function getShareToken(uint256 _outcome) public view returns (IShareToken); function getMarketCreatorSettlementFeeDivisor() public view returns (uint256); function getForkingMarket() public view returns (IMarket _market); function getEndTime() public view returns (uint256); function getWinningPayoutDistributionHash() public view returns (bytes32); function getWinningPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningReportingParticipant() public view returns (IReportingParticipant); function getReputationToken() public view returns (IV2ReputationToken); function getFinalizationTime() public view returns (uint256); function getInitialReporter() public view returns (IInitialReporter); function getDesignatedReportingEndTime() public view returns (uint256); function getValidityBondAttoCash() public view returns (uint256); function deriveMarketCreatorFeeAmount(uint256 _amount) public view returns (uint256); function recordMarketCreatorFees(uint256 _marketCreatorFees, address _affiliateAddress) public returns (bool); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isInvalid() public view returns (bool); function finalize() public returns (bool); function designatedReporterWasCorrect() public view returns (bool); function designatedReporterShowed() public view returns (bool); function isFinalized() public view returns (bool); function assertBalances() public view returns (bool); } contract IDisputeWindow is ITyped, IERC20 { uint256 public invalidMarketsTotal; uint256 public validityBondTotal; uint256 public incorrectDesignatedReportTotal; uint256 public initialReportBondTotal; uint256 public designatedReportNoShowsTotal; uint256 public designatedReporterNoShowBondTotal; function initialize(IAugur _augur, IUniverse _universe, uint256 _disputeWindowId, uint256 _duration, uint256 _startTime, address _erc1820RegistryAddress) public; function trustedBuy(address _buyer, uint256 _attotokens) public returns (bool); function getUniverse() public view returns (IUniverse); function getReputationToken() public view returns (IReputationToken); function getStartTime() public view returns (uint256); function getEndTime() public view returns (uint256); function getWindowId() public view returns (uint256); function isActive() public view returns (bool); function isOver() public view returns (bool); function onMarketFinalized() public; function redeem(address _account) public returns (bool); } contract IUniverse { mapping(address => uint256) public marketBalance; function fork() public returns (bool); function updateForkValues() public returns (bool); function getParentUniverse() public view returns (IUniverse); function createChildUniverse(uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse); function getReputationToken() public view returns (IV2ReputationToken); function getForkingMarket() public view returns (IMarket); function getForkEndTime() public view returns (uint256); function getForkReputationGoal() public view returns (uint256); function getParentPayoutDistributionHash() public view returns (bytes32); function getDisputeRoundDurationInSeconds(bool _initial) public view returns (uint256); function getOrCreateDisputeWindowByTimestamp(uint256 _timestamp, bool _initial) public returns (IDisputeWindow); function getOrCreateCurrentDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreateNextDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOrCreatePreviousDisputeWindow(bool _initial) public returns (IDisputeWindow); function getOpenInterestInAttoCash() public view returns (uint256); function getRepMarketCapInAttoCash() public view returns (uint256); function getTargetRepMarketCapInAttoCash() public view returns (uint256); function getOrCacheValidityBond() public returns (uint256); function getOrCacheDesignatedReportStake() public returns (uint256); function getOrCacheDesignatedReportNoShowBond() public returns (uint256); function getOrCacheMarketRepBond() public returns (uint256); function getOrCacheReportingFeeDivisor() public returns (uint256); function getDisputeThresholdForFork() public view returns (uint256); function getDisputeThresholdForDisputePacing() public view returns (uint256); function getInitialReportMinValue() public view returns (uint256); function getPayoutNumerators() public view returns (uint256[] memory); function getReportingFeeDivisor() public view returns (uint256); function getPayoutNumerator(uint256 _outcome) public view returns (uint256); function getWinningChildPayoutNumerator(uint256 _outcome) public view returns (uint256); function isOpenInterestCash(address) public view returns (bool); function isForkingMarket() public view returns (bool); function getCurrentDisputeWindow(bool _initial) public view returns (IDisputeWindow); function isParentOf(IUniverse _shadyChild) public view returns (bool); function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool); function isContainerForDisputeWindow(IDisputeWindow _shadyTarget) public view returns (bool); function isContainerForMarket(IMarket _shadyTarget) public view returns (bool); function isContainerForReportingParticipant(IReportingParticipant _reportingParticipant) public view returns (bool); function isContainerForShareToken(IShareToken _shadyTarget) public view returns (bool); function migrateMarketOut(IUniverse _destinationUniverse) public returns (bool); function migrateMarketIn(IMarket _market, uint256 _cashBalance, uint256 _marketOI) public returns (bool); function decrementOpenInterest(uint256 _amount) public returns (bool); function decrementOpenInterestFromMarket(IMarket _market) public returns (bool); function incrementOpenInterest(uint256 _amount) public returns (bool); function getWinningChildUniverse() public view returns (IUniverse); function isForking() public view returns (bool); function assertMarketBalance() public view returns (bool); function deposit(address _sender, uint256 _amount, address _market) public returns (bool); function withdraw(address _recipient, uint256 _amount, address _market) public returns (bool); } contract IAugur { function createChildUniverse(bytes32 _parentPayoutDistributionHash, uint256[] memory _parentPayoutNumerators) public returns (IUniverse); function isKnownUniverse(IUniverse _universe) public view returns (bool); function trustedTransfer(IERC20 _token, address _from, address _to, uint256 _amount) public returns (bool); function isTrustedSender(address _address) public returns (bool); function logCategoricalMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, bytes32[] memory _outcomes) public returns (bool); function logYesNoMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash) public returns (bool); function logScalarMarketCreated(uint256 _endTime, string memory _extraInfo, IMarket _market, address _marketCreator, address _designatedReporter, uint256 _feePerCashInAttoCash, int256[] memory _prices, uint256 _numTicks) public returns (bool); function logInitialReportSubmitted(IUniverse _universe, address _reporter, address _market, uint256 _amountStaked, bool _isDesignatedReporter, uint256[] memory _payoutNumerators, string memory _description, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime) public returns (bool); function disputeCrowdsourcerCreated(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _size, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerContribution(IUniverse _universe, address _reporter, address _market, address _disputeCrowdsourcer, uint256 _amountStaked, string memory description, uint256[] memory _payoutNumerators, uint256 _currentStake, uint256 _stakeRemaining, uint256 _disputeRound) public returns (bool); function logDisputeCrowdsourcerCompleted(IUniverse _universe, address _market, address _disputeCrowdsourcer, uint256[] memory _payoutNumerators, uint256 _nextWindowStartTime, uint256 _nextWindowEndTime, bool _pacingOn, uint256 _totalRepStakedInPayout, uint256 _totalRepStakedInMarket, uint256 _disputeRound) public returns (bool); function logInitialReporterRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logDisputeCrowdsourcerRedeemed(IUniverse _universe, address _reporter, address _market, uint256 _amountRedeemed, uint256 _repReceived, uint256[] memory _payoutNumerators) public returns (bool); function logMarketFinalized(IUniverse _universe, uint256[] memory _winningPayoutNumerators) public returns (bool); function logMarketMigrated(IMarket _market, IUniverse _originalUniverse) public returns (bool); function logReportingParticipantDisavowed(IUniverse _universe, IMarket _market) public returns (bool); function logMarketParticipantsDisavowed(IUniverse _universe) public returns (bool); function logOrderCanceled(IUniverse _universe, IMarket _market, address _creator, uint256 _tokenRefund, uint256 _sharesRefund, bytes32 _orderId) public returns (bool); function logOrderCreated(IUniverse _universe, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logOrderFilled(IUniverse _universe, address _creator, address _filler, uint256 _price, uint256 _fees, uint256 _amountFilled, bytes32 _orderId, bytes32 _tradeGroupId) public returns (bool); function logZeroXOrderFilled(IUniverse _universe, IMarket _market, bytes32 _tradeGroupId, Order.Types _orderType, address[] memory _addressData, uint256[] memory _uint256Data) public returns (bool); function logCompleteSetsPurchased(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets) public returns (bool); function logCompleteSetsSold(IUniverse _universe, IMarket _market, address _account, uint256 _numCompleteSets, uint256 _fees) public returns (bool); function logMarketOIChanged(IUniverse _universe, IMarket _market) public returns (bool); function logTradingProceedsClaimed(IUniverse _universe, address _shareToken, address _sender, address _market, uint256 _outcome, uint256 _numShares, uint256 _numPayoutTokens, uint256 _finalTokenBalance, uint256 _fees) public returns (bool); function logUniverseForked(IMarket _forkingMarket) public returns (bool); function logShareTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance, uint256 _outcome) public returns (bool); function logReputationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logReputationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logReputationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logShareTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance, uint256 _outcome) public returns (bool); function logShareTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance, uint256 _outcome) public returns (bool); function logDisputeCrowdsourcerTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logDisputeCrowdsourcerTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeCrowdsourcerTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logDisputeWindowCreated(IDisputeWindow _disputeWindow, uint256 _id, bool _initial) public returns (bool); function logParticipationTokensRedeemed(IUniverse universe, address _sender, uint256 _attoParticipationTokens, uint256 _feePayoutShare) public returns (bool); function logTimestampSet(uint256 _newTimestamp) public returns (bool); function logInitialReporterTransferred(IUniverse _universe, IMarket _market, address _from, address _to) public returns (bool); function logMarketTransferred(IUniverse _universe, address _from, address _to) public returns (bool); function logParticipationTokensTransferred(IUniverse _universe, address _from, address _to, uint256 _value, uint256 _fromBalance, uint256 _toBalance) public returns (bool); function logParticipationTokensBurned(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logParticipationTokensMinted(IUniverse _universe, address _target, uint256 _amount, uint256 _totalSupply, uint256 _balance) public returns (bool); function logMarketVolumeChanged(IUniverse _universe, address _market, uint256 _volume, uint256[] memory _outcomeVolumes) public returns (bool); function logProfitLossChanged(IMarket _market, address _account, uint256 _outcome, int256 _netPosition, uint256 _avgPrice, int256 _realizedProfit, int256 _frozenFunds, int256 _realizedCost) public returns (bool); function isKnownFeeSender(address _feeSender) public view returns (bool); function isKnownShareToken(IShareToken _token) public view returns (bool); function lookup(bytes32 _key) public view returns (address); function getTimestamp() public view returns (uint256); function getMaximumMarketEndDate() public returns (uint256); function isKnownMarket(IMarket _market) public view returns (bool); function derivePayoutDistributionHash(uint256[] memory _payoutNumerators, uint256 _numTicks, uint256 numOutcomes) public view returns (bytes32); } /** * @title SafeMathUint256 * @dev Uint256 math operations with safety checks that throw on error */ library SafeMathUint256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a <= b) { return a; } else { return b; } } function max(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a; } else { return b; } } function getUint256Min() internal pure returns (uint256) { return 0; } function getUint256Max() internal pure returns (uint256) { // 2 ** 256 - 1 return 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; } function isMultipleOf(uint256 a, uint256 b) internal pure returns (bool) { return a % b == 0; } // Float [fixed point] Operations function fxpMul(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, b), base); } function fxpDiv(uint256 a, uint256 b, uint256 base) internal pure returns (uint256) { return div(mul(a, base), b); } } // CONSIDER: Is `price` the most appropriate name for the value being used? It does correspond 1:1 with the attoCASH per share, but the range might be considered unusual? library Order { using SafeMathUint256 for uint256; enum Types { Bid, Ask } enum TradeDirections { Long, Short } struct Data { // Contracts IOrders orders; IMarket market; IAugur augur; IERC20 kycToken; ICash cash; // Order bytes32 id; address creator; uint256 outcome; Order.Types orderType; uint256 amount; uint256 price; uint256 sharesEscrowed; uint256 moneyEscrowed; bytes32 betterOrderId; bytes32 worseOrderId; } // No validation is needed here as it is simply a library function for organizing data function create(IAugur _augur, address _creator, uint256 _outcome, Order.Types _type, uint256 _attoshares, uint256 _price, IMarket _market, bytes32 _betterOrderId, bytes32 _worseOrderId, IERC20 _kycToken) internal view returns (Data memory) { require(_outcome < _market.getNumberOfOutcomes(), "Order.create: Outcome is not within market range"); require(_price != 0, "Order.create: Price may not be 0"); require(_price < _market.getNumTicks(), "Order.create: Price is outside of market range"); require(_attoshares > 0, "Order.create: Cannot use amount of 0"); require(_creator != address(0), "Order.create: Creator is 0x0"); IOrders _orders = IOrders(_augur.lookup("Orders")); return Data({ orders: _orders, market: _market, augur: _augur, kycToken: _kycToken, cash: ICash(_augur.lookup("Cash")), id: 0, creator: _creator, outcome: _outcome, orderType: _type, amount: _attoshares, price: _price, sharesEscrowed: 0, moneyEscrowed: 0, betterOrderId: _betterOrderId, worseOrderId: _worseOrderId }); } // // "public" functions // function getOrderId(Order.Data memory _orderData) internal view returns (bytes32) { if (_orderData.id == bytes32(0)) { bytes32 _orderId = _orderData.orders.getOrderId(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, block.number, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.kycToken); require(_orderData.orders.getAmount(_orderId) == 0, "Order.getOrderId: New order had amount. This should not be possible"); _orderData.id = _orderId; } return _orderData.id; } function getOrderTradingTypeFromMakerDirection(Order.TradeDirections _creatorDirection) internal pure returns (Order.Types) { return (_creatorDirection == Order.TradeDirections.Long) ? Order.Types.Bid : Order.Types.Ask; } function getOrderTradingTypeFromFillerDirection(Order.TradeDirections _fillerDirection) internal pure returns (Order.Types) { return (_fillerDirection == Order.TradeDirections.Long) ? Order.Types.Ask : Order.Types.Bid; } function escrowFunds(Order.Data memory _orderData) internal returns (bool) { if (_orderData.orderType == Order.Types.Ask) { return escrowFundsForAsk(_orderData); } else if (_orderData.orderType == Order.Types.Bid) { return escrowFundsForBid(_orderData); } } function saveOrder(Order.Data memory _orderData, bytes32 _tradeGroupId) internal returns (bytes32) { return _orderData.orders.saveOrder(_orderData.orderType, _orderData.market, _orderData.amount, _orderData.price, _orderData.creator, _orderData.outcome, _orderData.moneyEscrowed, _orderData.sharesEscrowed, _orderData.betterOrderId, _orderData.worseOrderId, _tradeGroupId, _orderData.kycToken); } // // Private functions // function escrowFundsForBid(Order.Data memory _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0, "Order.escrowFundsForBid: New order had money escrowed. This should not be possible"); require(_orderData.sharesEscrowed == 0, "Order.escrowFundsForBid: New order had shares escrowed. This should not be possible"); uint256 _attosharesToCover = _orderData.amount; uint256 _numberOfOutcomes = _orderData.market.getNumberOfOutcomes(); // Figure out how many almost-complete-sets (just missing `outcome` share) the creator has uint256 _attosharesHeld = 2**254; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { uint256 _creatorShareTokenBalance = _orderData.market.getShareToken(_i).balanceOf(_orderData.creator); _attosharesHeld = SafeMathUint256.min(_creatorShareTokenBalance, _attosharesHeld); } } // Take shares into escrow if they have any almost-complete-sets if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; for (uint256 _i = 0; _i < _numberOfOutcomes; _i++) { if (_i != _orderData.outcome) { _orderData.market.getShareToken(_i).trustedOrderTransfer(_orderData.creator, address(_orderData.market), _orderData.sharesEscrowed); } } } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _attosharesToCover.mul(_orderData.price); _orderData.market.getUniverse().deposit(_orderData.creator, _orderData.moneyEscrowed, address(_orderData.market)); } return true; } function escrowFundsForAsk(Order.Data memory _orderData) private returns (bool) { require(_orderData.moneyEscrowed == 0, "Order.escrowFundsForAsk: New order had money escrowed. This should not be possible"); require(_orderData.sharesEscrowed == 0, "Order.escrowFundsForAsk: New order had shares escrowed. This should not be possible"); IShareToken _shareToken = _orderData.market.getShareToken(_orderData.outcome); uint256 _attosharesToCover = _orderData.amount; // Figure out how many shares of the outcome the creator has uint256 _attosharesHeld = _shareToken.balanceOf(_orderData.creator); // Take shares in escrow if user has shares if (_attosharesHeld > 0) { _orderData.sharesEscrowed = SafeMathUint256.min(_attosharesHeld, _attosharesToCover); _attosharesToCover -= _orderData.sharesEscrowed; _shareToken.trustedOrderTransfer(_orderData.creator, address(_orderData.market), _orderData.sharesEscrowed); } // If not able to cover entire order with shares alone, then cover remaining with tokens if (_attosharesToCover > 0) { _orderData.moneyEscrowed = _orderData.market.getNumTicks().sub(_orderData.price).mul(_attosharesToCover); _orderData.market.getUniverse().deposit(_orderData.creator, _orderData.moneyEscrowed, address(_orderData.market)); } return true; } } contract IOrders { function saveOrder(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _betterOrderId, bytes32 _worseOrderId, bytes32 _tradeGroupId, IERC20 _kycToken) external returns (bytes32 _orderId); function removeOrder(bytes32 _orderId) external returns (bool); function getMarket(bytes32 _orderId) public view returns (IMarket); function getOrderType(bytes32 _orderId) public view returns (Order.Types); function getOutcome(bytes32 _orderId) public view returns (uint256); function getAmount(bytes32 _orderId) public view returns (uint256); function getPrice(bytes32 _orderId) public view returns (uint256); function getOrderCreator(bytes32 _orderId) public view returns (address); function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256); function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types, address[] memory _addressData, uint256[] memory _uint256Data); function getBetterOrderId(bytes32 _orderId) public view returns (bytes32); function getWorseOrderId(bytes32 _orderId) public view returns (bytes32); function getKYCToken(bytes32 _orderId) public view returns (IERC20); function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32); function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32); function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256); function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, IERC20 _kycToken) public pure returns (bytes32); function getTotalEscrowed(IMarket _market) public view returns (uint256); function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool); function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool); function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool); function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool); function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool); } /** * @title SafeMathInt256 * @dev Int256 math operations with safety checks that throw on error */ library SafeMathInt256 { // Signed ints with n bits can range from -2**(n-1) to (2**(n-1) - 1) int256 private constant INT256_MIN = -2**(255); int256 private constant INT256_MAX = (2**(255) - 1); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(a == 0 || c / a == b); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // No need to check for dividing by 0 -- Solidity automatically throws on division by 0 int256 c = a / b; return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require(((a >= 0) && (b >= a - INT256_MAX)) || ((a < 0) && (b <= a - INT256_MIN))); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { require(((a >= 0) && (b <= INT256_MAX - a)) || ((a < 0) && (b >= INT256_MIN - a))); return a + b; } function min(int256 a, int256 b) internal pure returns (int256) { if (a <= b) { return a; } else { return b; } } function max(int256 a, int256 b) internal pure returns (int256) { if (a >= b) { return a; } else { return b; } } function abs(int256 a) internal pure returns (int256) { if (a < 0) { return -a; } return a; } function getInt256Min() internal pure returns (int256) { return INT256_MIN; } function getInt256Max() internal pure returns (int256) { return INT256_MAX; } // Float [fixed point] Operations function fxpMul(int256 a, int256 b, int256 base) internal pure returns (int256) { return div(mul(a, b), base); } function fxpDiv(int256 a, int256 b, int256 base) internal pure returns (int256) { return div(mul(a, base), b); } } contract Initializable { bool private initialized = false; modifier beforeInitialized { require(!initialized); _; } function endInitialization() internal beforeInitialized { initialized = true; } function getInitialized() public view returns (bool) { return initialized; } } contract IProfitLoss { function initialize(IAugur _augur) public; function recordFrozenFundChange(IMarket _market, address _account, uint256 _outcome, int256 _frozenFundDelta) public returns (bool); function adjustTraderProfitForFees(IMarket _market, address _trader, uint256 _outcome, uint256 _fees) public returns (bool); function recordTrade(IMarket _market, address _longAddress, address _shortAddress, uint256 _outcome, int256 _amount, int256 _price, uint256 _numLongTokens, uint256 _numShortTokens, uint256 _numLongShares, uint256 _numShortShares) public returns (bool); function recordClaim(IMarket _market, address _account, uint256[] memory _outcomeFees) public returns (bool); function recordExternalTransfer(address _source, address _destination, uint256 _value) public returns (bool); } /** * @title Orders * @notice Storage of all data associated with orders */ contract Orders is IOrders, Initializable { using Order for Order.Data; using SafeMathUint256 for uint256; struct MarketOrders { uint256 totalEscrowed; mapping(uint256 => uint256) prices; } mapping(bytes32 => Order.Data) private orders; mapping(address => MarketOrders) private marketOrderData; mapping(bytes32 => bytes32) private bestOrder; mapping(bytes32 => bytes32) private worstOrder; IAugur public augur; ICash public cash; address public trade; address public fillOrder; address public cancelOrder; address public createOrder; IProfitLoss public profitLoss; function initialize(IAugur _augur) public beforeInitialized { endInitialization(); augur = _augur; createOrder = augur.lookup("CreateOrder"); fillOrder = augur.lookup("FillOrder"); cancelOrder = augur.lookup("CancelOrder"); trade = augur.lookup("Trade"); cash = ICash(augur.lookup("Cash")); profitLoss = IProfitLoss(augur.lookup("ProfitLoss")); } /** * @param _orderId The id of the order * @return The market associated with the order id */ function getMarket(bytes32 _orderId) public view returns (IMarket) { return orders[_orderId].market; } /** * @param _orderId The id of the order * @return The order type (BID==0,ASK==1) associated with the order */ function getOrderType(bytes32 _orderId) public view returns (Order.Types) { return orders[_orderId].orderType; } /** * @param _orderId The id of the order * @return The outcome associated with the order */ function getOutcome(bytes32 _orderId) public view returns (uint256) { return orders[_orderId].outcome; } /** * @param _orderId The id of the order * @return The KYC token associated with the order */ function getKYCToken(bytes32 _orderId) public view returns (IERC20) { return orders[_orderId].kycToken; } /** * @param _orderId The id of the order * @return The remaining amount of the order */ function getAmount(bytes32 _orderId) public view returns (uint256) { return orders[_orderId].amount; } /** * @param _orderId The id of the order * @return The price of the order */ function getPrice(bytes32 _orderId) public view returns (uint256) { return orders[_orderId].price; } /** * @param _orderId The id of the order * @return The creator of the order */ function getOrderCreator(bytes32 _orderId) public view returns (address) { return orders[_orderId].creator; } /** * @param _orderId The id of the order * @return The remaining shares escrowed in the order */ function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256) { return orders[_orderId].sharesEscrowed; } /** * @param _orderId The id of the order * @return The remaining Cash tokens escrowed in the order */ function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256) { return orders[_orderId].moneyEscrowed; } function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types _type, address[] memory _addressData, uint256[] memory _uint256Data) { Order.Data storage _order = orders[_orderId]; _addressData = new address[](3); _uint256Data = new uint256[](10); _addressData[0] = address(_order.kycToken); _addressData[1] = _order.creator; _uint256Data[0] = _order.price; _uint256Data[1] = _order.amount; _uint256Data[2] = _order.outcome; _uint256Data[8] = _order.sharesEscrowed; _uint256Data[9] = _order.moneyEscrowed; return (_order.orderType, _addressData, _uint256Data); } /** * @param _market The address of the market * @return The amount of Cash escrowed for all orders for the specified market */ function getTotalEscrowed(IMarket _market) public view returns (uint256) { return marketOrderData[address(_market)].totalEscrowed; } /** * @param _market The address of the market * @param _outcome The outcome number * @return The price for the last completed trade for the specified market and outcome */ function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256) { return marketOrderData[address(_market)].prices[_outcome]; } /** * @param _orderId The id of the order * @return The id (if there is one) of the next order better than the provided one */ function getBetterOrderId(bytes32 _orderId) public view returns (bytes32) { return orders[_orderId].betterOrderId; } /** * @param _orderId The id of the order * @return The id (if there is one) of the next order worse than the provided one */ function getWorseOrderId(bytes32 _orderId) public view returns (bytes32) { return orders[_orderId].worseOrderId; } /** * @param _type The type of order. Either BID==0, or ASK==1 * @param _market The market of the order * @param _outcome The outcome of the order * @param _kycToken The KYC token of the order * @return The id (if there is one) of the best order that satisfies the given parameters */ function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32) { return bestOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)]; } /** * @param _type The type of order. Either BID==0, or ASK==1 * @param _market The market of the order * @param _outcome The outcome of the order * @param _kycToken The KYC token of the order * @return The id (if there is one) of the worst order that satisfies the given parameters */ function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32) { return worstOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)]; } /** * @param _type The type of order. Either BID==0, or ASK==1 * @param _market The market of the order * @param _amount The amount of the order * @param _price The price of the order * @param _sender The creator of the order * @param _blockNumber The blockNumber which the order was created in * @param _outcome The outcome of the order * @param _moneyEscrowed The amount of Cash tokens escrowed in the order * @param _sharesEscrowed The outcome Share tokens escrowed in the order * @param _kycToken The KYC token of the order * @return The order id that satisfies the given parameters */ function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, IERC20 _kycToken) public pure returns (bytes32) { return sha256(abi.encodePacked(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed, _kycToken)); } function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool) { if (_type == Order.Types.Bid) { return (_price > orders[_orderId].price); } else if (_type == Order.Types.Ask) { return (_price < orders[_orderId].price); } } function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool) { if (_type == Order.Types.Bid) { return (_price <= orders[_orderId].price); } else { return (_price >= orders[_orderId].price); } } function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool) { require(!isBetterPrice(_type, _price, _betterOrderId), "Orders.assertIsNotBetterPrice: Is better price"); return true; } function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool) { require(!isWorsePrice(_type, _price, _worseOrderId), "Orders.assertIsNotWorsePrice: Is worse price"); return true; } function insertOrderIntoList(Order.Data storage _order, bytes32 _betterOrderId, bytes32 _worseOrderId) private returns (bool) { bytes32 _bestOrderId = bestOrder[getBestOrderWorstOrderHash(_order.market, _order.outcome, _order.orderType, _order.kycToken)]; bytes32 _worstOrderId = worstOrder[getBestOrderWorstOrderHash(_order.market, _order.outcome, _order.orderType, _order.kycToken)]; (_betterOrderId, _worseOrderId) = findBoundingOrders(_order.orderType, _order.price, _bestOrderId, _worstOrderId, _betterOrderId, _worseOrderId); if (_order.orderType == Order.Types.Bid) { _bestOrderId = updateBestBidOrder(_order.id, _order.market, _order.price, _order.outcome, _order.kycToken); _worstOrderId = updateWorstBidOrder(_order.id, _order.market, _order.price, _order.outcome, _order.kycToken); } else { _bestOrderId = updateBestAskOrder(_order.id, _order.market, _order.price, _order.outcome, _order.kycToken); _worstOrderId = updateWorstAskOrder(_order.id, _order.market, _order.price, _order.outcome, _order.kycToken); } if (_bestOrderId == _order.id) { _betterOrderId = bytes32(0); } if (_worstOrderId == _order.id) { _worseOrderId = bytes32(0); } if (_betterOrderId != bytes32(0)) { orders[_betterOrderId].worseOrderId = _order.id; _order.betterOrderId = _betterOrderId; } if (_worseOrderId != bytes32(0)) { orders[_worseOrderId].betterOrderId = _order.id; _order.worseOrderId = _worseOrderId; } return true; } function saveOrder(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, bytes32 _betterOrderId, bytes32 _worseOrderId, bytes32 _tradeGroupId, IERC20 _kycToken) external returns (bytes32 _orderId) { require(msg.sender == createOrder || msg.sender == address(this)); require(_outcome < _market.getNumberOfOutcomes(), "Orders.saveOrder: Outcome not in market range"); _orderId = getOrderId(_type, _market, _amount, _price, _sender, block.number, _outcome, _moneyEscrowed, _sharesEscrowed, _kycToken); Order.Data storage _order = orders[_orderId]; _order.orders = this; _order.market = _market; _order.id = _orderId; _order.orderType = _type; _order.outcome = _outcome; _order.price = _price; _order.amount = _amount; _order.creator = _sender; _order.kycToken = _kycToken; _order.moneyEscrowed = _moneyEscrowed; marketOrderData[address(_market)].totalEscrowed += _moneyEscrowed; _order.sharesEscrowed = _sharesEscrowed; insertOrderIntoList(_order, _betterOrderId, _worseOrderId); augur.logOrderCreated(_order.market.getUniverse(), _orderId, _tradeGroupId); return _orderId; } function removeOrder(bytes32 _orderId) external returns (bool) { require(msg.sender == cancelOrder || msg.sender == address(this)); removeOrderFromList(_orderId); Order.Data storage _order = orders[_orderId]; marketOrderData[address(_order.market)].totalEscrowed -= _order.moneyEscrowed; delete orders[_orderId]; return true; } function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool) { require(msg.sender == fillOrder || msg.sender == address(this)); Order.Data storage _order = orders[_orderId]; require(_order.outcome < _order.market.getNumberOfOutcomes(), "Orders.recordFillOrder: Outcome is not in market range"); require(_orderId != bytes32(0), "Orders.recordFillOrder: orderId is 0x0"); require(_sharesFilled <= _order.sharesEscrowed, "Orders.recordFillOrder: shares filled higher than order amount"); require(_tokensFilled <= _order.moneyEscrowed, "Orders.recordFillOrder: tokens filled higher than order amount"); require(_order.price <= _order.market.getNumTicks(), "Orders.recordFillOrder: Price outside of market range"); require(_fill <= _order.amount, "Orders.recordFillOrder: Fill higher than order amount"); _order.amount -= _fill; _order.moneyEscrowed -= _tokensFilled; marketOrderData[address(_order.market)].totalEscrowed -= _tokensFilled; _order.sharesEscrowed -= _sharesFilled; if (_order.amount == 0) { require(_order.moneyEscrowed == 0, "Orders.recordFillOrder: Money left in filled order"); require(_order.sharesEscrowed == 0, "Orders.recordFillOrder: Shares left in filled order"); removeOrderFromList(_orderId); _order.price = 0; _order.creator = address(0); _order.betterOrderId = bytes32(0); _order.worseOrderId = bytes32(0); } return true; } function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool) { require(msg.sender == trade); marketOrderData[address(_market)].prices[_outcome] = _price; return true; } function removeOrderFromList(bytes32 _orderId) private returns (bool) { Order.Types _type = orders[_orderId].orderType; IMarket _market = orders[_orderId].market; uint256 _outcome = orders[_orderId].outcome; IERC20 _kycToken = orders[_orderId].kycToken; bytes32 _betterOrderId = orders[_orderId].betterOrderId; bytes32 _worseOrderId = orders[_orderId].worseOrderId; if (bestOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)] == _orderId) { bestOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)] = _worseOrderId; } if (worstOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)] == _orderId) { worstOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)] = _betterOrderId; } if (_betterOrderId != bytes32(0)) { orders[_betterOrderId].worseOrderId = _worseOrderId; } if (_worseOrderId != bytes32(0)) { orders[_worseOrderId].betterOrderId = _betterOrderId; } orders[_orderId].betterOrderId = bytes32(0); orders[_orderId].worseOrderId = bytes32(0); return true; } /** * @dev If best bid is not set or price higher than best bid price, this order is the new best bid. */ function updateBestBidOrder(bytes32 _orderId, IMarket _market, uint256 _price, uint256 _outcome, IERC20 _kycToken) private returns (bytes32) { bytes32 _bestBidOrderId = bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)]; if (_bestBidOrderId == bytes32(0) || _price > orders[_bestBidOrderId].price) { bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)] = _orderId; } return bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)]; } /** * @dev If worst bid is not set or price lower than worst bid price, this order is the new worst bid. */ function updateWorstBidOrder(bytes32 _orderId, IMarket _market, uint256 _price, uint256 _outcome, IERC20 _kycToken) private returns (bytes32) { bytes32 _worstBidOrderId = worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)]; if (_worstBidOrderId == bytes32(0) || _price <= orders[_worstBidOrderId].price) { worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)] = _orderId; } return worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Bid, _kycToken)]; } /** * @dev If best ask is not set or price lower than best ask price, this order is the new best ask. */ function updateBestAskOrder(bytes32 _orderId, IMarket _market, uint256 _price, uint256 _outcome, IERC20 _kycToken) private returns (bytes32) { bytes32 _bestAskOrderId = bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; if (_bestAskOrderId == bytes32(0) || _price < orders[_bestAskOrderId].price) { bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)] = _orderId; } return bestOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; } /** * @dev If worst ask is not set or price higher than worst ask price, this order is the new worst ask. */ function updateWorstAskOrder(bytes32 _orderId, IMarket _market, uint256 _price, uint256 _outcome, IERC20 _kycToken) private returns (bytes32) { bytes32 _worstAskOrderId = worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; if (_worstAskOrderId == bytes32(0) || _price >= orders[_worstAskOrderId].price) { worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)] = _orderId; } return worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; } function getBestOrderWorstOrderHash(IMarket _market, uint256 _outcome, Order.Types _type, IERC20 _kycToken) private pure returns (bytes32) { return sha256(abi.encodePacked(_market, _outcome, _type, _kycToken)); } function ascendOrderList(Order.Types _type, uint256 _price, bytes32 _lowestOrderId) public view returns (bytes32 _betterOrderId, bytes32 _worseOrderId) { _worseOrderId = _lowestOrderId; bool _isWorstPrice; if (_type == Order.Types.Bid) { _isWorstPrice = _price <= getPrice(_worseOrderId); } else if (_type == Order.Types.Ask) { _isWorstPrice = _price >= getPrice(_worseOrderId); } if (_isWorstPrice) { return (_worseOrderId, getWorseOrderId(_worseOrderId)); } bool _isBetterPrice = isBetterPrice(_type, _price, _worseOrderId); while (_isBetterPrice && getBetterOrderId(_worseOrderId) != 0 && _price != getPrice(getBetterOrderId(_worseOrderId))) { _betterOrderId = getBetterOrderId(_worseOrderId); _isBetterPrice = isBetterPrice(_type, _price, _betterOrderId); if (_isBetterPrice) { _worseOrderId = getBetterOrderId(_worseOrderId); } } _betterOrderId = getBetterOrderId(_worseOrderId); return (_betterOrderId, _worseOrderId); } function descendOrderList(Order.Types _type, uint256 _price, bytes32 _highestOrderId) public view returns (bytes32 _betterOrderId, bytes32 _worseOrderId) { _betterOrderId = _highestOrderId; bool _isBestPrice; if (_type == Order.Types.Bid) { _isBestPrice = _price > getPrice(_betterOrderId); } else if (_type == Order.Types.Ask) { _isBestPrice = _price < getPrice(_betterOrderId); } if (_isBestPrice) { return (0, _betterOrderId); } bool _isWorsePrice = isWorsePrice(_type, _price, _betterOrderId); while (_isWorsePrice && getWorseOrderId(_betterOrderId) != 0) { _worseOrderId = getWorseOrderId(_betterOrderId); _isWorsePrice = isWorsePrice(_type, _price, _worseOrderId); if (_isWorsePrice || _price == getPrice(getWorseOrderId(_betterOrderId))) { _betterOrderId = getWorseOrderId(_betterOrderId); } } _worseOrderId = getWorseOrderId(_betterOrderId); return (_betterOrderId, _worseOrderId); } function findBoundingOrders(Order.Types _type, uint256 _price, bytes32 _bestOrderId, bytes32 _worstOrderId, bytes32 _betterOrderId, bytes32 _worseOrderId) public returns (bytes32 betterOrderId, bytes32 worseOrderId) { if (_bestOrderId == _worstOrderId) { if (_bestOrderId == bytes32(0)) { return (bytes32(0), bytes32(0)); } else if (isBetterPrice(_type, _price, _bestOrderId)) { return (bytes32(0), _bestOrderId); } else { return (_bestOrderId, bytes32(0)); } } if (_betterOrderId != bytes32(0)) { if (getPrice(_betterOrderId) == 0) { _betterOrderId = bytes32(0); } else { assertIsNotBetterPrice(_type, _price, _betterOrderId); } } if (_worseOrderId != bytes32(0)) { if (getPrice(_worseOrderId) == 0) { _worseOrderId = bytes32(0); } else { assertIsNotWorsePrice(_type, _price, _worseOrderId); } } if (_betterOrderId == bytes32(0) && _worseOrderId == bytes32(0)) { return (descendOrderList(_type, _price, _bestOrderId)); } else if (_betterOrderId == bytes32(0)) { return (ascendOrderList(_type, _price, _worseOrderId)); } else if (_worseOrderId == bytes32(0)) { return (descendOrderList(_type, _price, _betterOrderId)); } if (getWorseOrderId(_betterOrderId) != _worseOrderId) { return (descendOrderList(_type, _price, _betterOrderId)); } else if (getBetterOrderId(_worseOrderId) != _betterOrderId) { // Coverage: This condition is likely unreachable or at least seems to be. Rather than remove it I'm keeping it for now just to be paranoid return (ascendOrderList(_type, _price, _worseOrderId)); } return (_betterOrderId, _worseOrderId); } }
If worst ask is not set or price higher than worst ask price, this order is the new worst ask./
function updateWorstAskOrder(bytes32 _orderId, IMarket _market, uint256 _price, uint256 _outcome, IERC20 _kycToken) private returns (bytes32) { bytes32 _worstAskOrderId = worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; if (_worstAskOrderId == bytes32(0) || _price >= orders[_worstAskOrderId].price) { worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)] = _orderId; } return worstOrder[getBestOrderWorstOrderHash(_market, _outcome, Order.Types.Ask, _kycToken)]; }
991,674
pragma solidity 0.4.25; /** * * ETHPROFIT.SPACE * * ETH CRYPTOCURRENCY DISTRIBUTION PROJECT * * - GAIN 3% PER 24 HOURS (interest is charges in equal parts every 10 min) * - Life-long payments * - The revolutionary reliability * - Minimal contribution 0.01 eth * - Currency and payment - ETH * - Contribution allocation schemes: * -- 90% payments * -- 8% marketing * -- 2% technical support * * ---How to use: * 1. Send from ETH wallet to the smart contract address * any amount from 0.01 ETH. * 2. Verify your transaction in the history of your application or etherscan.io, specifying the address * of your wallet. * 3a. Claim your profit by sending 0 ether transaction (every 10 min, every day, every week, i don't care unless you're * spending too much on GAS) * OR * 3b. For reinvest, you need to deposit the amount that you want to reinvest and the * accrued interest automatically summed to your new contribution. * * RECOMMENDED GAS LIMIT: 250000 * RECOMMENDED GAS PRICE: https://ethgasstation.info/ * You can check the payments on the etherscan.io site, in the "Internal Txns" tab of your wallet. * * ---Refferral system: remuneration to each contributor is 3%, * * ---It is not allowed to transfer from exchanges, only from your personal ETH wallet, for which you * have private keys. * * Contracts reviewed and approved by pros! * */ library Math { function min(uint a, uint b) internal pure returns(uint) { if (a > b) { return b; } return a; } } library Zero { function requireNotZero(address addr) internal pure { require(addr != address(0), "require not zero address"); } function requireNotZero(uint val) internal pure { require(val != 0, "require not zero value"); } function notZero(address addr) internal pure returns(bool) { return !(addr == address(0)); } function isZero(address addr) internal pure returns(bool) { return addr == address(0); } function isZero(uint a) internal pure returns(bool) { return a == 0; } function notZero(uint a) internal pure returns(bool) { return a != 0; } } library Percent { // Solidity automatically throws when dividing by 0 struct percent { uint num; uint den; } // storage function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function div(percent storage p, uint a) internal view returns (uint) { return a/p.num*p.den; } function sub(percent storage p, uint a) internal view returns (uint) { uint b = mul(p, a); if (b >= a) { return 0; } return a - b; } function add(percent storage p, uint a) internal view returns (uint) { return a + mul(p, a); } function toMemory(percent storage p) internal view returns (Percent.percent memory) { return Percent.percent(p.num, p.den); } // memory function mmul(percent memory p, uint a) internal pure returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function mdiv(percent memory p, uint a) internal pure returns (uint) { return a/p.num*p.den; } function msub(percent memory p, uint a) internal pure returns (uint) { uint b = mmul(p, a); if (b >= a) { return 0; } return a - b; } function madd(percent memory p, uint a) internal pure returns (uint) { return a + mmul(p, a); } } library Address { function toAddress(bytes source) internal pure returns(address addr) { assembly { addr := mload(add(source,0x14)) } return addr; } function isNotContract(address addr) internal view returns(bool) { uint length; assembly { length := extcodesize(addr) } return length == 0; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Accessibility { address private owner; modifier onlyOwner() { require(msg.sender == owner, "access denied"); _; } constructor() public { owner = msg.sender; } function disown() internal { delete owner; } } contract InvestorsStorage is Accessibility { struct Investor { uint investment; uint paymentTime; } uint public size; mapping (address => Investor) private investors; function isInvestor(address addr) public view returns (bool) { return investors[addr].investment > 0; } function investorInfo(address addr) public view returns(uint investment, uint paymentTime) { investment = investors[addr].investment; paymentTime = investors[addr].paymentTime; } function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) { Investor storage inv = investors[addr]; if (inv.investment != 0 || investment == 0) { return false; } inv.investment = investment; inv.paymentTime = paymentTime; size++; return true; } function addInvestment(address addr, uint investment) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].investment += investment; return true; } function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].paymentTime = paymentTime; return true; } } contract Ethprofitspace is Accessibility { using Percent for Percent.percent; using SafeMath for uint; using Math for uint; // easy read for investors using Address for *; using Zero for *; mapping(address => bool) private m_referrals; InvestorsStorage private m_investors; // automatically generates getters uint public constant minInvesment = 10 finney; // 0.01 eth uint public constant maxBalance = 100e5 ether; // 10 000 000 eth address public advertisingAddress; address public adminsAddress; uint public investmentsNumber; uint public waveStartup; // percents Percent.percent private m_3_percent = Percent.percent(3, 100); // 3/100*100% = 3% Percent.percent private m_adminsPercent = Percent.percent(2, 100); // 2/100 *100% = 2% Percent.percent private m_advertisingPercent = Percent.percent(8, 100);// 8/100 *100% = 8% // more events for easy read from blockchain event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess); event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus); event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogAutomaticReinvest(address indexed addr, uint when, uint investment); event LogPayDividends(address indexed addr, uint when, uint dividends); event LogNewInvestor(address indexed addr, uint when); event LogBalanceChanged(uint when, uint balance); event LogNextWave(uint when); event LogDisown(uint when); modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } constructor() public { adminsAddress = msg.sender; advertisingAddress = msg.sender; nextWave(); } function() public payable { // investor get him dividends if (msg.value.isZero()) { getMyDividends(); return; } // sender do invest doInvest(msg.data.toAddress()); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function setAdvertisingAddress(address addr) public onlyOwner { addr.requireNotZero(); advertisingAddress = addr; } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function investorsNumber() public view returns(uint) { return m_investors.size(); } function balanceETH() public view returns(uint) { return address(this).balance; } function percent3() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_3_percent.num, m_3_percent.den); } function advertisingPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den); } function adminsPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den); } function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) { (investment, paymentTime) = m_investors.investorInfo(investorAddr); isReferral = m_referrals[investorAddr]; } function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) { dividends = calcDividends(investorAddr); } function dailyPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = dailyPercent(); (numerator, denominator) = (p.num, p.den); } function refBonusPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = refBonusPercent(); (numerator, denominator) = (p.num, p.den); } function getMyDividends() public notFromContract balanceChanged { // calculate dividends uint dividends = calcDividends(msg.sender); require (dividends.notZero(), "cannot to pay zero dividends"); // update investor payment timestamp assert(m_investors.setPaymentTime(msg.sender, now)); // check enough eth - goto next wave if needed if (address(this).balance <= dividends) { nextWave(); dividends = address(this).balance; } // transfer dividends to investor msg.sender.transfer(dividends); emit LogPayDividends(msg.sender, now, dividends); } function doInvest(address referrerAddr) public payable notFromContract balanceChanged { uint investment = msg.value; uint receivedEther = msg.value; require(investment >= minInvesment, "investment must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); // send excess of ether if needed if (receivedEther > investment) { uint excess = receivedEther - investment; msg.sender.transfer(excess); receivedEther = investment; emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess); } // commission advertisingAddress.send(m_advertisingPercent.mul(receivedEther)); adminsAddress.send(m_adminsPercent.mul(receivedEther)); bool senderIsInvestor = m_investors.isInvestor(msg.sender); // ref system works only once and only on first invest if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] && referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) { m_referrals[msg.sender] = true; // add referral bonus to investor`s and referral`s investments uint refBonus = refBonusPercent().mmul(investment); assert(m_investors.addInvestment(referrerAddr, refBonus)); // add referrer bonus investment += refBonus; // add referral bonus emit LogNewReferral(msg.sender, referrerAddr, now, refBonus); } // automatic reinvest - prevent burning dividends uint dividends = calcDividends(msg.sender); if (senderIsInvestor && dividends.notZero()) { investment += dividends; emit LogAutomaticReinvest(msg.sender, now, dividends); } if (senderIsInvestor) { // update existing investor assert(m_investors.addInvestment(msg.sender, investment)); assert(m_investors.setPaymentTime(msg.sender, now)); } else { // create new investor assert(m_investors.newInvestor(msg.sender, investment, now)); emit LogNewInvestor(msg.sender, now); } investmentsNumber++; emit LogNewInvesment(msg.sender, now, investment, receivedEther); } function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) { (uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr); return InvestorsStorage.Investor(investment, paymentTime); } function calcDividends(address investorAddr) internal view returns(uint dividends) { InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr); // safe gas if dividends will be 0 if (investor.investment.isZero() || now.sub(investor.paymentTime) < 10 minutes) { return 0; } // for prevent burning daily dividends if 24h did not pass - calculate it per 10 min interval // if daily percent is X, then 10min percent = X / (24h / 10 min) = X / 144 // and we must to get numbers of 10 min interval after investor got payment: // (now - investor.paymentTime) / 10min // finaly calculate dividends = ((now - investor.paymentTime) / 10min) * (X * investor.investment) / 144) Percent.percent memory p = dailyPercent(); dividends = (now.sub(investor.paymentTime) / 10 minutes) * p.mmul(investor.investment) / 144; } function dailyPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; // (3) 3% if balance < 10 000 000 ETH if (balance < 10000000 ether) { p = m_3_percent.toMemory(); // (3) } } function refBonusPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; // (3) 3% if balance < 10 000 000 ETH if (balance < 10000000 ether) { p = m_3_percent.toMemory(); // (3) } } function nextWave() private { m_investors = new InvestorsStorage(); investmentsNumber = 0; waveStartup = now; emit LogNextWave(now); } }
(3) 3% if balance < 10 000 000 ETH
function dailyPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; if (balance < 10000000 ether) { } }
7,242,022
./partial_match/1/0xdcA642D5F821599A328bb6f282C86d95f6AE8C36/sources/BBNB.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Buyback N Burn", "BBNB") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyBuybackFee = 10; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellBuybackFee = 30; uint256 totalSupply = 100000000000 * 1e18; maxTransactionAmount = totalSupply * 20 / 1000; maxWallet = totalSupply * 20 / 1000; swapTokensAtAmount = totalSupply * 5 / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyBuybackFee = _buyBuybackFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBuybackFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellBuybackFee = _sellBuybackFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBuybackFee; marketingWallet = address(owner()); devWallet = address(owner()); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
3,930,777
./full_match/80001/0x9E2fB73B223a35ef5C83Bf7722aaE83aAb86e430/sources/contracts/LUCIANSOULS.sol
1. Override the claim function to ensure a few things: - They own an NFT from the TICKET contract - They own an NFT from the SOUL contract
function verifyClaim( address _claimer, uint256 _tokenId, uint256 _quantity ) public view virtual override{ if (_tokenId >= 2) { require(this.balanceOf(_claimer, 0) >= _quantity, "You don't own enough TICKET NFTs"); require(this.balanceOf(_claimer, 0) >= _quantity, "You don't own enough SOUL NFTs"); } }
5,666,765
pragma solidity ^0.8.3; import "./LoanRouter.sol"; import "./interfaces/IBondController.sol"; import "./interfaces/ITranche.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev Loan router for the UniswapV3 AMM */ contract UniV3LoanRouter is LoanRouter { ISwapRouter public uniswapV3Router; constructor(ISwapRouter _uniswapV3Router) { uniswapV3Router = _uniswapV3Router; } /** * @inheritdoc LoanRouter */ function _swap( address input, address output, uint256 amount ) internal override { IERC20(input).approve(address(uniswapV3Router), amount); uniswapV3Router.exactInputSingle( ISwapRouter.ExactInputSingleParams( address(input), address(output), 3000, address(this), block.timestamp, amount, 0, 0 ) ); } } pragma solidity ^0.8.3; import "./interfaces/ILoanRouter.sol"; import "./interfaces/IBondController.sol"; import "./interfaces/ITranche.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @dev Abstract Loan Router to allow loans to be created with different AMM implementations * Loans are created using a composition of ButtonTranche and an AMM for Tranche token liquidity * vs. a stablecoin. The specific AMM that we use may change, so concrete implementations * of this abstract contract can define a `swap` function to implement a composition with * the AMM of their choosing. */ abstract contract LoanRouter is ILoanRouter { uint256 public constant MAX_UINT256 = type(uint256).max; /** * @inheritdoc ILoanRouter */ function borrow( uint256 amount, IBondController bond, IERC20 currency, uint256[] memory sales, uint256 minOutput ) external override returns (uint256 amountOut) { return _borrow(amount, bond, currency, sales, minOutput); } /** * @inheritdoc ILoanRouter */ function borrowMax( uint256 amount, IBondController bond, IERC20 currency, uint256 minOutput ) external override returns (uint256 amountOut) { uint256 trancheCount = bond.trancheCount(); uint256[] memory sales = new uint256[](trancheCount); // sell all tokens except the last one (Z token) for (uint256 i = 0; i < trancheCount - 1; i++) { sales[i] = MAX_UINT256; } return _borrow(amount, bond, currency, sales, minOutput); } /** * @dev Internal function to borrow a given currency from a given collateral * @param amount The amount of the collateral to deposit * @param bond The bond to deposit with * @param currency The currency to borrow * @param sales The amount of each tranche to sell for the currency. * If MAX_UNT256, then sell full balance of the token * @param minOutput The minimum amount of currency that should be recived, else reverts */ function _borrow( uint256 amount, IBondController bond, IERC20 currency, uint256[] memory sales, uint256 minOutput ) internal returns (uint256 amountOut) { IERC20 collateral = IERC20(bond.collateralToken()); require(address(collateral) != address(currency), "LoanRouter: Invalid currency"); SafeERC20.safeTransferFrom(collateral, msg.sender, address(this), amount); collateral.approve(address(bond), amount); bond.deposit(amount); uint256 trancheCount = bond.trancheCount(); require(trancheCount == sales.length, "LoanRouter: Invalid sales"); ITranche tranche; for (uint256 i = 0; i < trancheCount; i++) { (tranche, ) = bond.tranches(i); uint256 sale = sales[i]; uint256 trancheBalance = tranche.balanceOf(address(this)); if (sale == MAX_UINT256) { sale = trancheBalance; } else if (sale == 0) { SafeERC20.safeTransfer(tranche, msg.sender, trancheBalance); continue; } else { // transfer any excess to the caller SafeERC20.safeTransfer(tranche, msg.sender, trancheBalance - sale); } _swap(address(tranche), address(currency), sale); } uint256 balance = currency.balanceOf(address(this)); require(balance >= minOutput, "LoanRouter: Insufficient output"); SafeERC20.safeTransfer(currency, msg.sender, balance); return balance; } /** * @dev Virtual function to define the swapping mechanism for a loan router * @param input The ERC20 token to input into the swap * @param output The ERC20 token to get out from the swap * @param amount The amount of input to put into the swap */ function _swap( address input, address output, uint256 amount ) internal virtual; } pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "./ITranche.sol"; struct TrancheData { ITranche token; uint256 ratio; } /** * @dev Controller for a ButtonTranche bond system */ interface IBondController { event Deposit(address from, uint256 amount, uint256 feeBps); event Mature(address caller); event RedeemMature(address user, address tranche, uint256 amount); event Redeem(address user, uint256[] amounts); event FeeUpdate(uint256 newFee); function collateralToken() external view returns (address); function tranches(uint256 i) external view returns (ITranche token, uint256 ratio); function trancheCount() external view returns (uint256 count); function feeBps() external view returns (uint256 fee); /** * @dev Deposit `amount` tokens from `msg.sender`, get tranche tokens in return * Requirements: * - `msg.sender` must have `approved` `amount` collateral tokens to this contract */ function deposit(uint256 amount) external; /** * @dev Matures the bond. Disables deposits, * fixes the redemption ratio, and distributes collateral to redemption pools * Redeems any fees collected from deposits, sending redeemed funds to the contract owner * Requirements: * - The bond is not already mature * - One of: * - `msg.sender` is owner * - `maturityDate` has passed */ function mature() external; /** * @dev Redeems some tranche tokens * Requirements: * - The bond is mature * - `msg.sender` owns at least `amount` tranche tokens from address `tranche` * - `tranche` must be a valid tranche token on this bond */ function redeemMature(address tranche, uint256 amount) external; /** * @dev Redeems a slice of tranche tokens from all tranches. * Returns collateral to the user proportionally to the amount of debt they are removing * Requirements * - The bond is not mature * - The number of `amounts` is the same as the number of tranches * - The `amounts` are in equivalent ratio to the tranche order */ function redeem(uint256[] memory amounts) external; /** * @dev Updates the fee taken on deposit to the given new fee * * Requirements * - `msg.sender` has admin role * - `newFeeBps` is in range [0, 50] */ function setFee(uint256 newFeeBps) external; } pragma solidity 0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * @dev ERC20 token to represent a single tranche for a ButtonTranche bond * */ interface ITranche is IERC20 { /** * @dev Mint `amount` tokens to `to` * Only callable by the owner (bond controller). Used to * manage bonds, specifically creating tokens upon deposit * @param to the address to mint tokens to * @param amount The amount of tokens to mint */ function mint(address to, uint256 amount) external; /** * @dev Burn `amount` tokens from `from`'s balance * Only callable by the owner (bond controller). Used to * manage bonds, specifically burning tokens upon redemption * @param from The address to burn tokens from * @param amount The amount of tokens to burn */ function burn(address from, uint256 amount) external; /** * @dev Burn `amount` tokens from `from` and return the proportional * value of the collateral token to `to` * @param from The address to burn tokens from * @param to The address to send collateral back to * @param amount The amount of tokens to burn */ function redeem( address from, address to, uint256 amount ) external; } // 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: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' 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"); } } } pragma solidity 0.8.3; import "./IBondController.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Router for creating loans with tranche */ interface ILoanRouter { function borrow( uint256 amount, IBondController bond, IERC20 currency, uint256[] memory sales, uint256 minOutput ) external returns (uint256 amountOut); function borrowMax( uint256 amount, IBondController bond, IERC20 currency, uint256 minOutput ) external returns (uint256 amountOut); } // 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: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: 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: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; }
Controller for a ButtonTranche bond system/
interface IBondController { event Deposit(address from, uint256 amount, uint256 feeBps); event Mature(address caller); event RedeemMature(address user, address tranche, uint256 amount); event Redeem(address user, uint256[] amounts); event FeeUpdate(uint256 newFee); function collateralToken() external view returns (address); function tranches(uint256 i) external view returns (ITranche token, uint256 ratio); function trancheCount() external view returns (uint256 count); function feeBps() external view returns (uint256 fee); function deposit(uint256 amount) external; function mature() external; function redeemMature(address tranche, uint256 amount) external; function redeem(uint256[] memory amounts) external; function setFee(uint256 newFeeBps) external; }
425,684
./partial_match/1/0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671/sources/NumeraireBackend.sol
Check if it is safe to subtract two numbers
function safeSubtract(uint a, uint b) internal returns (uint) { uint c = a - b; assert(b <= a && c <= a); return c; }
4,382,407
./full_match/5/0x12C0758b11f16157306F04336B1399FAc36679D2/sources/contracts/bankroll/facets/BankrollFacet.sol
Permantly suspend player. This function sets suspension time to the maximum allowed time./
function permantlyBan() external { gs().suspendedTime[msg.sender] = 2 ** 256 - 1; gs().isPlayerSuspended[msg.sender] = true; }
7,040,554
// Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 pragma solidity ^0.4.8; contract SafeMath { function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { uint256 constant MAX_UINT256 = 2**256 - 1; bool public isFrozen; // switched to true in frozen state function transfer(address _to, uint256 _value) returns (bool success) { if (isFrozen) revert(); //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (isFrozen) revert(); //same as above. Replace this line with the following if you want to protect against wrapping uints. //require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract PreAdsMobileToken is StandardToken, SafeMath { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals = 18; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H0.1'; //human 0.1 standard. Just an arbitrary versioning scheme. // contracts address public ethFundDeposit; // deposit address for ETH for AdsMobile // crowdsale parameters bool public isFinalized; // switched to true in operational state uint256 public fundingStartBlock; uint256 public fundingEndBlock; uint256 public checkNumber; uint256 public totalSupplyWithOutBonus; uint256 public constant tokenExchangeRate = 400; // 400 AdsMobile tokens per 1 ETH uint256 public constant tokenCreationCapWithOutBonus = 3 * (10**6) * 10**18; uint256 public constant tokenNeedForBonusLevel0 = 100 * (10**3) * 10**18; uint256 public constant bonusLevel0PercentModifier = 300; uint256 public constant tokenNeedForBonusLevel1 = 50 * (10**3) * 10**18; uint256 public constant bonusLevel1PercentModifier = 200; uint256 public constant tokenCreationMinPayment = 50 * (10**3) * 10**18; // events event CreateAds(address indexed _to, uint256 _value); // constructor function PreAdsMobileToken( string _tokenName, string _tokenSymbol, address _ethFundDeposit, uint256 _fundingStartBlock, uint256 _fundingEndBlock ) { balances[msg.sender] = 0; // Give the creator all initial tokens totalSupply = 0; // Update total supply name = _tokenName; // Set the name for display purposes decimals = 18; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes isFinalized = false; // controls pre through crowdsale state isFrozen = false; ethFundDeposit = _ethFundDeposit; fundingStartBlock = _fundingStartBlock; fundingEndBlock = _fundingEndBlock; checkNumber = 42; //Answer to the Ultimate Question of Life, the Universe, and Everything } /// @dev Accepts ether and creates new ADS tokens. function createTokens() public payable { if (isFinalized) revert(); if (block.number < fundingStartBlock) revert(); if (block.number > fundingEndBlock) revert(); if (msg.value == 0) revert(); uint256 tokensWithOutBonus = safeMult(msg.value, tokenExchangeRate); // check that we're not over totals if (tokensWithOutBonus < tokenCreationMinPayment) revert(); uint256 checkedSupplyWithOutBonus = safeAdd(totalSupplyWithOutBonus, tokensWithOutBonus); // return money if something goes wrong if (tokenCreationCapWithOutBonus < checkedSupplyWithOutBonus) revert(); // odd fractions won't be found totalSupplyWithOutBonus = checkedSupplyWithOutBonus; uint256 tokens = tokensWithOutBonus; if(tokens >= tokenNeedForBonusLevel0) { tokens = safeDiv(tokens, 100); tokens = safeMult(tokens, bonusLevel0PercentModifier); } else { if(tokens >= tokenNeedForBonusLevel1) { tokens = safeDiv(tokens, 100); tokens = safeMult(tokens, bonusLevel1PercentModifier); } } uint256 checkedSupply = safeAdd(totalSupply, tokens); totalSupply = checkedSupply; balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here CreateAds(msg.sender, tokens); // logs token creation } //just for test cashin and cashout on small amount before let it go function cashin() external payable { if (isFinalized) revert(); } function cashout(uint256 amount) external { if (isFinalized) revert(); if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner if (!ethFundDeposit.send(amount)) revert(); // send the eth to AdsMobile } //in case we want to transfer token to other contract we need freeze all future transfers function freeze() external { if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner isFrozen = true; } function unFreeze() external { if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner isFrozen = false; } /// @dev Ends the funding period and sends the ETH home function finalize() external { if (isFinalized) revert(); if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner if (block.number <= fundingEndBlock && totalSupplyWithOutBonus < tokenCreationCapWithOutBonus - tokenCreationMinPayment) revert(); // move to operational if (!ethFundDeposit.send(this.balance)) revert(); // send the eth to AdsMobile isFinalized = true; } /** * @dev Fallback function which receives ether and created the appropriate number of tokens for the * msg.sender. */ function() external payable { createTokens(); } }
Ends the funding period and sends the ETH home move to operational
function finalize() external { if (isFinalized) revert(); if (block.number <= fundingEndBlock && totalSupplyWithOutBonus < tokenCreationCapWithOutBonus - tokenCreationMinPayment) revert(); isFinalized = true; }
7,239,121
./partial_match/1/0xBEE571A0A8599adA125e1A33E56287c3c594a5e2/sources/MYIDENTITYCOIN.sol
totalSupply : Display total supply of token/
function totalSupply() virtual override public view returns (uint) { return _totalSupply; }
2,581,659
./full_match/5/0xcc92C04f5EF23801616Be4929a85c394659274a9/sources/contracts/PropertyNFT.sol
Batch Mint an NFT in one transaction
function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts ) public onlyAuthorized { emit MintBatch(to, ids, amounts); _mintBatch(to, ids, amounts, ""); }
1,933,312
// 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 { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Library/IERC20.sol pragma solidity ^0.5.14; interface IERC20 { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: contracts/Library/SafeMath.sol pragma solidity ^0.5.14; /** * @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: contracts/Library/Freezer.sol pragma solidity ^0.5.14; /** * @title Freezer * @author Yoonsung * @notice This Contracts is an extension of the ERC20. Transfer * of a specific address can be blocked from by the Owner of the * Token Contract. */ contract Freezer is Ownable { event Freezed(address dsc); event Unfreezed(address dsc); mapping (address => bool) public freezing; modifier isFreezed (address src) { require(freezing[src] == false, "Freeze/Fronzen-Account"); _; } /** * @notice The Freeze function sets the transfer limit * for a specific address. * @param _dsc address The specify address want to limit the transfer. */ function freeze(address _dsc) external onlyOwner { require(_dsc != address(0), "Freeze/Zero-Address"); require(freezing[_dsc] == false, "Freeze/Already-Freezed"); freezing[_dsc] = true; emit Freezed(_dsc); } /** * @notice The Freeze function removes the transfer limit * for a specific address. * @param _dsc address The specify address want to remove the transfer. */ function unFreeze(address _dsc) external onlyOwner { require(freezing[_dsc] == true, "Freeze/Already-Unfreezed"); delete freezing[_dsc]; emit Unfreezed(_dsc); } } // File: contracts/Library/SendLimiter.sol pragma solidity ^0.5.14; /** * @title SendLimiter * @author Yoonsung * @notice This contract acts as an ERC20 extension. It must * be called from the creator of the ERC20, and a modifier is * provided that can be used together. This contract is short-lived. * You cannot re-enable it after SendUnlock, to be careful. Provides * a set of functions to manage the addresses that can be sent. */ contract SendLimiter is Ownable { event SendWhitelisted(address dsc); event SendDelisted(address dsc); event SendUnlocked(); bool public sendLimit; mapping (address => bool) public sendWhitelist; /** * @notice In constructor, Set Send Limit exceptionally msg.sender. * constructor is used, the restriction is activated. */ constructor() public { sendLimit = true; sendWhitelist[msg.sender] = true; } modifier isAllowedSend (address dsc) { if (sendLimit) require(sendWhitelist[dsc], "SendLimiter/Not-Allow-Address"); _; } /** * @notice Register the address that you want to allow to be sent. * @param _whiteAddress address The specify what to send target. */ function addAllowSender(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "SendLimiter/Not-Allow-Zero-Address"); sendWhitelist[_whiteAddress] = true; emit SendWhitelisted(_whiteAddress); } /** * @notice Register the addresses that you want to allow to be sent. * @param _whiteAddresses address[] The specify what to send target. */ function addAllowSenders(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { addAllowSender(_whiteAddresses[i]); } } /** * @notice Remove the address that you want to allow to be sent. * @param _whiteAddress address The specify what to send target. */ function removeAllowedSender(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "SendLimiter/Not-Allow-Zero-Address"); delete sendWhitelist[_whiteAddress]; emit SendDelisted(_whiteAddress); } /** * @notice Remove the addresses that you want to allow to be sent. * @param _whiteAddresses address[] The specify what to send target. */ function removeAllowedSenders(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { removeAllowedSender(_whiteAddresses[i]); } } /** * @notice Revoke transfer restrictions. */ function sendUnlock() external onlyOwner { sendLimit = false; emit SendUnlocked(); } } // File: contracts/Library/ReceiveLimiter.sol pragma solidity ^0.5.14; /** * @title ReceiveLimiter * @author Yoonsung * @notice This contract acts as an ERC20 extension. It must * be called from the creator of the ERC20, and a modifier is * provided that can be used together. This contract is short-lived. * You cannot re-enable it after ReceiveUnlock, to be careful. Provides * a set of functions to manage the addresses that can be sent. */ contract ReceiveLimiter is Ownable { event ReceiveWhitelisted(address dsc); event ReceiveDelisted(address dsc); event ReceiveUnlocked(); bool public receiveLimit; mapping (address => bool) public receiveWhitelist; /** * @notice In constructor, Set Receive Limit exceptionally msg.sender. * constructor is used, the restriction is activated. */ constructor() public { receiveLimit = true; receiveWhitelist[msg.sender] = true; } modifier isAllowedReceive (address dsc) { if (receiveLimit) require(receiveWhitelist[dsc], "Limiter/Not-Allow-Address"); _; } /** * @notice Register the address that you want to allow to be receive. * @param _whiteAddress address The specify what to receive target. */ function addAllowReceiver(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "Limiter/Not-Allow-Zero-Address"); receiveWhitelist[_whiteAddress] = true; emit ReceiveWhitelisted(_whiteAddress); } /** * @notice Register the addresses that you want to allow to be receive. * @param _whiteAddresses address[] The specify what to receive target. */ function addAllowReceivers(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { addAllowReceiver(_whiteAddresses[i]); } } /** * @notice Remove the address that you want to allow to be receive. * @param _whiteAddress address The specify what to receive target. */ function removeAllowedReceiver(address _whiteAddress) public onlyOwner { require(_whiteAddress != address(0), "Limiter/Not-Allow-Zero-Address"); delete receiveWhitelist[_whiteAddress]; emit ReceiveDelisted(_whiteAddress); } /** * @notice Remove the addresses that you want to allow to be receive. * @param _whiteAddresses address[] The specify what to receive target. */ function removeAllowedReceivers(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { removeAllowedReceiver(_whiteAddresses[i]); } } /** * @notice Revoke Receive restrictions. */ function receiveUnlock() external onlyOwner { receiveLimit = false; emit ReceiveUnlocked(); } } // File: contracts/TokenAsset.sol pragma solidity ^0.5.14; /** * @title TokenAsset * @author Yoonsung * @notice This Contract is an implementation of TokenAsset's ERC20 * Basic ERC20 functions and "Burn" functions are implemented. For the * Burn function, only the Owner of Contract can be called and used * to incinerate unsold Token. Transfer and reception limits are imposed * after the contract is distributed and can be revoked through SendUnlock * and ReceiveUnlock. Don't do active again after cancellation. The Owner * may also suspend the transfer of a particular account at any time. */ contract TokenAsset is Ownable, IERC20, SendLimiter, ReceiveLimiter, Freezer { using SafeMath for uint256; string public constant name = "tokenAsset"; string public constant symbol = "NTB"; uint8 public constant decimals = 18; uint256 public totalSupply = 200000000e18; mapping (address => uint256) public balanceOf; mapping (address => mapping(address => uint256)) public allowance; /** * @notice In constructor, Set Send Limit and Receive Limits. * Additionally, Contract's publisher is authorized to own all tokens. */ constructor() SendLimiter() ReceiveLimiter() public { balanceOf[msg.sender] = totalSupply; } /** * @notice Transfer function sends Token to the target. However, * caller must have more tokens than or equal to the quantity for send. * @param _to address The specify what to send target. * @param _value uint256 The amount of token to tranfer. * @return True if the withdrawal succeeded, otherwise revert. */ function transfer ( address _to, uint256 _value ) external isAllowedSend(msg.sender) isAllowedReceive(_to) isFreezed(msg.sender) returns (bool) { require(_to != address(0), "TokenAsset/Not-Allow-Zero-Address"); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @notice Transfer function sends Token to the target. * In most cases, the allowed caller uses this function. Send * Token instead of owner. Allowance address must have more * tokens than or equal to the quantity for send. * @param _from address The acoount to sender. * @param _to address The specify what to send target. * @param _value uint256 The amount of token to tranfer. * @return True if the withdrawal succeeded, otherwise revert. */ function transferFrom ( address _from, address _to, uint256 _value ) external isAllowedSend(_from) isAllowedReceive(_to) isFreezed(_from) returns (bool) { require(_from != address(0), "TokenAsset/Not-Allow-Zero-Address"); require(_to != address(0), "TokenAsset/Not-Allow-Zero-Address"); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @notice The Owner of the Contracts incinerate own * Token. burn unsold Token and reduce totalsupply. Caller * must have more tokens than or equal to the quantity for send. * @param _value uint256 The amount of incinerate token. * @return True if the withdrawal succeeded, otherwise revert. */ function burn ( uint256 _value ) external returns (bool) { require(_value <= balanceOf[msg.sender]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Transfer(msg.sender, address(0), _value); return true; } /** * @notice Allow specific address to send token instead. * @param _spender address The address to send transaction on my behalf * @param _value uint256 The amount on my behalf, Usually 0 or uint256(-1). * @return True if the withdrawal succeeded, otherwise revert. */ function approve ( address _spender, uint256 _value ) external returns (bool) { require(_spender != address(0), "TokenAsset/Not-Allow-Zero-Address"); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } }
Register the addresses that you want to allow to be receive. _whiteAddresses address[] The specify what to receive target./
function addAllowReceivers(address[] memory _whiteAddresses) public onlyOwner { for (uint256 i = 0; i < _whiteAddresses.length; i++) { addAllowReceiver(_whiteAddresses[i]); } }
12,838,342
/** *Submitted for verification at Etherscan.io on 2020-10-11 */ // File: solidity/contracts/utility/interfaces/IOwned.sol // SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; /* Owned contract interface */ interface IOwned { // this function isn't since the compiler emits automatically generated getter functions as external function owner() external view returns (address); function transferOwnership(address _newOwner) external; function acceptOwnership() external; } // File: solidity/contracts/converter/interfaces/IConverterAnchor.sol pragma solidity 0.6.12; /* Converter Anchor interface */ interface IConverterAnchor is IOwned { } // File: solidity/contracts/token/interfaces/IERC20Token.sol pragma solidity 0.6.12; /* ERC20 Standard Token interface */ interface IERC20Token { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function approve(address _spender, uint256 _value) external returns (bool); } // File: solidity/contracts/utility/interfaces/IWhitelist.sol pragma solidity 0.6.12; /* Whitelist interface */ interface IWhitelist { function isWhitelisted(address _address) external view returns (bool); } // File: solidity/contracts/converter/interfaces/IConverter.sol pragma solidity 0.6.12; /* Converter interface */ interface IConverter is IOwned { function converterType() external pure returns (uint16); function anchor() external view returns (IConverterAnchor); function isActive() external view returns (bool); function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) external view returns (uint256, uint256); function convert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) external payable returns (uint256); function conversionWhitelist() external view returns (IWhitelist); function conversionFee() external view returns (uint32); function maxConversionFee() external view returns (uint32); function reserveBalance(IERC20Token _reserveToken) external view returns (uint256); receive() external payable; function transferAnchorOwnership(address _newOwner) external; function acceptAnchorOwnership() external; function setConversionFee(uint32 _conversionFee) external; function setConversionWhitelist(IWhitelist _whitelist) external; function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) external; function withdrawETH(address payable _to) external; function addReserve(IERC20Token _token, uint32 _ratio) external; // deprecated, backward compatibility function token() external view returns (IConverterAnchor); function transferTokenOwnership(address _newOwner) external; function acceptTokenOwnership() external; function connectors(IERC20Token _address) external view returns (uint256, uint32, bool, bool, bool); function getConnectorBalance(IERC20Token _connectorToken) external view returns (uint256); function connectorTokens(uint256 _index) external view returns (IERC20Token); function connectorTokenCount() external view returns (uint16); } // File: solidity/contracts/converter/interfaces/IConverterUpgrader.sol pragma solidity 0.6.12; /* Converter Upgrader interface */ interface IConverterUpgrader { function upgrade(bytes32 _version) external; function upgrade(uint16 _version) external; } // File: solidity/contracts/converter/interfaces/IBancorFormula.sol pragma solidity 0.6.12; /* Bancor Formula interface */ interface IBancorFormula { function purchaseTargetAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) external view returns (uint256); function saleTargetAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) external view returns (uint256); function crossReserveTargetAmount(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) external view returns (uint256); function fundCost(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) external view returns (uint256); function fundSupplyAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) external view returns (uint256); function liquidateReserveAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) external view returns (uint256); function balancedWeights(uint256 _primaryReserveStakedBalance, uint256 _primaryReserveBalance, uint256 _secondaryReserveBalance, uint256 _reserveRateNumerator, uint256 _reserveRateDenominator) external view returns (uint32, uint32); } // File: solidity/contracts/utility/Owned.sol pragma solidity 0.6.12; /** * @dev Provides support and utilities for contract ownership */ contract Owned is IOwned { address public override owner; address public newOwner; /** * @dev triggered when the owner is updated * * @param _prevOwner previous owner * @param _newOwner new owner */ event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner); /** * @dev initializes a new Owned instance */ constructor() public { owner = msg.sender; } // allows execution by the owner only modifier ownerOnly { _ownerOnly(); _; } // error message binary size optimization function _ownerOnly() internal view { require(msg.sender == owner, "ERR_ACCESS_DENIED"); } /** * @dev allows transferring the contract ownership * the new owner still needs to accept the transfer * can only be called by the contract owner * * @param _newOwner new contract owner */ function transferOwnership(address _newOwner) public override ownerOnly { require(_newOwner != owner, "ERR_SAME_OWNER"); newOwner = _newOwner; } /** * @dev used by a new owner to accept an ownership transfer */ function acceptOwnership() override public { require(msg.sender == newOwner, "ERR_ACCESS_DENIED"); emit OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = address(0); } } // File: solidity/contracts/utility/Utils.sol pragma solidity 0.6.12; /** * @dev Utilities & Common Modifiers */ contract Utils { // verifies that a value is greater than zero modifier greaterThanZero(uint256 _value) { _greaterThanZero(_value); _; } // error message binary size optimization function _greaterThanZero(uint256 _value) internal pure { require(_value > 0, "ERR_ZERO_VALUE"); } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { _validAddress(_address); _; } // error message binary size optimization function _validAddress(address _address) internal pure { require(_address != address(0), "ERR_INVALID_ADDRESS"); } // verifies that the address is different than this contract address modifier notThis(address _address) { _notThis(_address); _; } // error message binary size optimization function _notThis(address _address) internal view { require(_address != address(this), "ERR_ADDRESS_IS_SELF"); } } // File: solidity/contracts/utility/interfaces/IContractRegistry.sol pragma solidity 0.6.12; /* Contract Registry interface */ interface IContractRegistry { function addressOf(bytes32 _contractName) external view returns (address); } // File: solidity/contracts/utility/ContractRegistryClient.sol pragma solidity 0.6.12; /** * @dev Base contract for ContractRegistry clients */ contract ContractRegistryClient is Owned, Utils { bytes32 internal constant CONTRACT_REGISTRY = "ContractRegistry"; bytes32 internal constant BANCOR_NETWORK = "BancorNetwork"; bytes32 internal constant BANCOR_FORMULA = "BancorFormula"; bytes32 internal constant CONVERTER_FACTORY = "ConverterFactory"; bytes32 internal constant CONVERSION_PATH_FINDER = "ConversionPathFinder"; bytes32 internal constant CONVERTER_UPGRADER = "BancorConverterUpgrader"; bytes32 internal constant CONVERTER_REGISTRY = "BancorConverterRegistry"; bytes32 internal constant CONVERTER_REGISTRY_DATA = "BancorConverterRegistryData"; bytes32 internal constant BNT_TOKEN = "BNTToken"; bytes32 internal constant BANCOR_X = "BancorX"; bytes32 internal constant BANCOR_X_UPGRADER = "BancorXUpgrader"; bytes32 internal constant CHAINLINK_ORACLE_WHITELIST = "ChainlinkOracleWhitelist"; IContractRegistry public registry; // address of the current contract-registry IContractRegistry public prevRegistry; // address of the previous contract-registry bool public onlyOwnerCanUpdateRegistry; // only an owner can update the contract-registry /** * @dev verifies that the caller is mapped to the given contract name * * @param _contractName contract name */ modifier only(bytes32 _contractName) { _only(_contractName); _; } // error message binary size optimization function _only(bytes32 _contractName) internal view { require(msg.sender == addressOf(_contractName), "ERR_ACCESS_DENIED"); } /** * @dev initializes a new ContractRegistryClient instance * * @param _registry address of a contract-registry contract */ constructor(IContractRegistry _registry) internal validAddress(address(_registry)) { registry = IContractRegistry(_registry); prevRegistry = IContractRegistry(_registry); } /** * @dev updates to the new contract-registry */ function updateRegistry() public { // verify that this function is permitted require(msg.sender == owner || !onlyOwnerCanUpdateRegistry, "ERR_ACCESS_DENIED"); // get the new contract-registry IContractRegistry newRegistry = IContractRegistry(addressOf(CONTRACT_REGISTRY)); // verify that the new contract-registry is different and not zero require(newRegistry != registry && address(newRegistry) != address(0), "ERR_INVALID_REGISTRY"); // verify that the new contract-registry is pointing to a non-zero contract-registry require(newRegistry.addressOf(CONTRACT_REGISTRY) != address(0), "ERR_INVALID_REGISTRY"); // save a backup of the current contract-registry before replacing it prevRegistry = registry; // replace the current contract-registry with the new contract-registry registry = newRegistry; } /** * @dev restores the previous contract-registry */ function restoreRegistry() public ownerOnly { // restore the previous contract-registry registry = prevRegistry; } /** * @dev restricts the permission to update the contract-registry * * @param _onlyOwnerCanUpdateRegistry indicates whether or not permission is restricted to owner only */ function restrictRegistryUpdate(bool _onlyOwnerCanUpdateRegistry) public ownerOnly { // change the permission to update the contract-registry onlyOwnerCanUpdateRegistry = _onlyOwnerCanUpdateRegistry; } /** * @dev returns the address associated with the given contract name * * @param _contractName contract name * * @return contract address */ function addressOf(bytes32 _contractName) internal view returns (address) { return registry.addressOf(_contractName); } } // File: solidity/contracts/utility/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev ReentrancyGuard * * The contract provides protection against re-entrancy - calling a function (directly or * indirectly) from within itself. */ contract ReentrancyGuard { uint256 private constant UNLOCKED = 1; uint256 private constant LOCKED = 2; // LOCKED while protected code is being executed, UNLOCKED otherwise uint256 private state = UNLOCKED; /** * @dev ensures instantiation only by sub-contracts */ constructor() internal {} // protects a function against reentrancy attacks modifier protected() { _protected(); state = LOCKED; _; state = UNLOCKED; } // error message binary size optimization function _protected() internal view { require(state == UNLOCKED, "ERR_REENTRANCY"); } } // File: solidity/contracts/utility/SafeMath.sol pragma solidity 0.6.12; /** * @dev Library for basic math operations with overflow/underflow protection */ library SafeMath { /** * @dev returns the sum of _x and _y, reverts if the calculation overflows * * @param _x value 1 * @param _y value 2 * * @return sum */ function add(uint256 _x, uint256 _y) internal pure returns (uint256) { uint256 z = _x + _y; require(z >= _x, "ERR_OVERFLOW"); return z; } /** * @dev returns the difference of _x minus _y, reverts if the calculation underflows * * @param _x minuend * @param _y subtrahend * * @return difference */ function sub(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_x >= _y, "ERR_UNDERFLOW"); return _x - _y; } /** * @dev returns the product of multiplying _x by _y, reverts if the calculation overflows * * @param _x factor 1 * @param _y factor 2 * * @return product */ function mul(uint256 _x, uint256 _y) internal pure returns (uint256) { // gas optimization if (_x == 0) return 0; uint256 z = _x * _y; require(z / _x == _y, "ERR_OVERFLOW"); return z; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. * * @param _x dividend * @param _y divisor * * @return quotient */ function div(uint256 _x, uint256 _y) internal pure returns (uint256) { require(_y > 0, "ERR_DIVIDE_BY_ZERO"); uint256 c = _x / _y; return c; } } // File: solidity/contracts/utility/TokenHandler.sol pragma solidity 0.6.12; contract TokenHandler { bytes4 private constant APPROVE_FUNC_SELECTOR = bytes4(keccak256("approve(address,uint256)")); bytes4 private constant TRANSFER_FUNC_SELECTOR = bytes4(keccak256("transfer(address,uint256)")); bytes4 private constant TRANSFER_FROM_FUNC_SELECTOR = bytes4(keccak256("transferFrom(address,address,uint256)")); /** * @dev executes the ERC20 token's `approve` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _spender approved address * @param _value allowance amount */ function safeApprove(IERC20Token _token, address _spender, uint256 _value) internal { (bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(APPROVE_FUNC_SELECTOR, _spender, _value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_APPROVE_FAILED'); } /** * @dev executes the ERC20 token's `transfer` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _to target address * @param _value transfer amount */ function safeTransfer(IERC20Token _token, address _to, uint256 _value) internal { (bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FUNC_SELECTOR, _to, _value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FAILED'); } /** * @dev executes the ERC20 token's `transferFrom` function and reverts upon failure * the main purpose of this function is to prevent a non standard ERC20 token * from failing silently * * @param _token ERC20 token address * @param _from source address * @param _to target address * @param _value transfer amount */ function safeTransferFrom(IERC20Token _token, address _from, address _to, uint256 _value) internal { (bool success, bytes memory data) = address(_token).call(abi.encodeWithSelector(TRANSFER_FROM_FUNC_SELECTOR, _from, _to, _value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ERR_TRANSFER_FROM_FAILED'); } } // File: solidity/contracts/utility/interfaces/ITokenHolder.sol pragma solidity 0.6.12; /* Token Holder interface */ interface ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) external; } // File: solidity/contracts/utility/TokenHolder.sol pragma solidity 0.6.12; /** * @dev We consider every contract to be a 'token holder' since it's currently not possible * for a contract to deny receiving tokens. * * The TokenHolder's contract sole purpose is to provide a safety mechanism that allows * the owner to send tokens that were sent to the contract by mistake back to their sender. * * Note that we use the non standard ERC-20 interface which has no return value for transfer * in order to support both non standard as well as standard token contracts. * see https://github.com/ethereum/solidity/issues/4116 */ contract TokenHolder is ITokenHolder, TokenHandler, Owned, Utils { /** * @dev withdraws tokens held by the contract and sends them to an account * can only be called by the owner * * @param _token ERC20 token contract address * @param _to account to receive the new amount * @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public virtual override ownerOnly validAddress(address(_token)) validAddress(_to) notThis(_to) { safeTransfer(_token, _to, _amount); } } // File: solidity/contracts/token/interfaces/IEtherToken.sol pragma solidity 0.6.12; /* Ether Token interface */ interface IEtherToken is IERC20Token { function deposit() external payable; function withdraw(uint256 _amount) external; function depositTo(address _to) external payable; function withdrawTo(address payable _to, uint256 _amount) external; } // File: solidity/contracts/bancorx/interfaces/IBancorX.sol pragma solidity 0.6.12; interface IBancorX { function token() external view returns (IERC20Token); function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount, uint256 _id) external; function getXTransferAmount(uint256 _xTransferId, address _for) external view returns (uint256); } // File: solidity/contracts/converter/ConverterBase.sol pragma solidity 0.6.12; /** * @dev ConverterBase * * The converter contains the main logic for conversions between different ERC20 tokens. * * It is also the upgradable part of the mechanism (note that upgrades are opt-in). * * The anchor must be set on construction and cannot be changed afterwards. * Wrappers are provided for some of the anchor's functions, for easier access. * * Once the converter accepts ownership of the anchor, it becomes the anchor's sole controller * and can execute any of its functions. * * To upgrade the converter, anchor ownership must be transferred to a new converter, along with * any relevant data. * * Note that the converter can transfer anchor ownership to a new converter that * doesn't allow upgrades anymore, for finalizing the relationship between the converter * and the anchor. * * Converter types (defined as uint16 type) - * 0 = liquid token converter * 1 = liquidity pool v1 converter * 2 = liquidity pool v2 converter * * Note that converters don't currently support tokens with transfer fees. */ abstract contract ConverterBase is IConverter, TokenHandler, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint32 internal constant PPM_RESOLUTION = 1000000; IERC20Token internal constant ETH_RESERVE_ADDRESS = IERC20Token(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); struct Reserve { uint256 balance; // reserve balance uint32 weight; // reserve weight, represented in ppm, 1-1000000 bool deprecated1; // deprecated bool deprecated2; // deprecated bool isSet; // true if the reserve is valid, false otherwise } /** * @dev version number */ uint16 public constant version = 41; IConverterAnchor public override anchor; // converter anchor contract IWhitelist public override conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead) mapping (IERC20Token => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead) uint32 public reserveRatio = 0; // ratio between the reserves and the market cap, equal to the total reserve weights uint32 public override maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public override conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public constant conversionsEnabled = true; // deprecated, backward compatibility /** * @dev triggered when the converter is activated * * @param _type converter type * @param _anchor converter anchor * @param _activated true if the converter was activated, false if it was deactivated */ event Activation(uint16 indexed _type, IConverterAnchor indexed _anchor, bool indexed _activated); /** * @dev triggered when a conversion between two tokens occurs * * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _trader wallet that initiated the trade * @param _amount amount converted, in the source token * @param _return amount returned, minus conversion fee * @param _conversionFee conversion fee */ event Conversion( IERC20Token indexed _fromToken, IERC20Token indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return, int256 _conversionFee ); /** * @dev triggered when the rate between two tokens in the converter changes * note that the event might be dispatched for rate updates between any two tokens in the converter * note that prior to version 28, you should use the 'PriceDataUpdate' event instead * * @param _token1 address of the first token * @param _token2 address of the second token * @param _rateN rate of 1 unit of `_token1` in `_token2` (numerator) * @param _rateD rate of 1 unit of `_token1` in `_token2` (denominator) */ event TokenRateUpdate( IERC20Token indexed _token1, IERC20Token indexed _token2, uint256 _rateN, uint256 _rateD ); /** * @dev triggered when the conversion fee is updated * * @param _prevFee previous fee percentage, represented in ppm * @param _newFee new fee percentage, represented in ppm */ event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); /** * @dev used by sub-contracts to initialize a new converter * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee ) validAddress(address(_anchor)) ContractRegistryClient(_registry) internal validConversionFee(_maxConversionFee) { anchor = _anchor; maxConversionFee = _maxConversionFee; } // ensures that the converter is active modifier active() { _active(); _; } // error message binary size optimization function _active() internal view { require(isActive(), "ERR_INACTIVE"); } // ensures that the converter is not active modifier inactive() { _inactive(); _; } // error message binary size optimization function _inactive() internal view { require(!isActive(), "ERR_ACTIVE"); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IERC20Token _address) { _validReserve(_address); _; } // error message binary size optimization function _validReserve(IERC20Token _address) internal view { require(reserves[_address].isSet, "ERR_INVALID_RESERVE"); } // validates conversion fee modifier validConversionFee(uint32 _conversionFee) { _validConversionFee(_conversionFee); _; } // error message binary size optimization function _validConversionFee(uint32 _conversionFee) internal pure { require(_conversionFee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE"); } // validates reserve weight modifier validReserveWeight(uint32 _weight) { _validReserveWeight(_weight); _; } // error message binary size optimization function _validReserveWeight(uint32 _weight) internal pure { require(_weight > 0 && _weight <= PPM_RESOLUTION, "ERR_INVALID_RESERVE_WEIGHT"); } // overrides interface declaration function converterType() public pure virtual override returns (uint16); // overrides interface declaration function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view virtual override returns (uint256, uint256); /** * @dev deposits ether * can only be called if the converter has an ETH reserve */ receive() external override payable { //injected LOCKED ETHER require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_INVALID_RESERVE"); // require(hasETHReserve(), "ERR_INVALID_RESERVE"); // a workaround for a problem when running solidity-coverage // see https://github.com/sc-forks/solidity-coverage/issues/487 } /** * @dev withdraws ether * can only be called by the owner if the converter is inactive or by upgrader contract * can only be called after the upgrader contract has accepted the ownership of this contract * can only be called if the converter has an ETH reserve * * @param _to address to send the ETH to */ function withdrawETH(address payable _to) public override protected ownerOnly validReserve(ETH_RESERVE_ADDRESS) { address converterUpgrader = addressOf(CONVERTER_UPGRADER); // verify that the converter is inactive or that the owner is the upgrader contract require(!isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED"); _to.transfer(0); // sync the ETH reserve balance syncReserveBalance(ETH_RESERVE_ADDRESS); } /** * @dev checks whether or not the converter version is 28 or higher * * @return true, since the converter version is 28 or higher */ function isV28OrHigher() public pure returns (bool) { return true; } /** * @dev allows the owner to update & enable the conversion whitelist contract address * when set, only addresses that are whitelisted are actually allowed to use the converter * note that the whitelist check is actually done by the BancorNetwork contract * * @param _whitelist address of a whitelist contract */ function setConversionWhitelist(IWhitelist _whitelist) public override ownerOnly notThis(address(_whitelist)) { conversionWhitelist = _whitelist; } /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public view virtual override returns (bool) { return anchor.owner() == address(this); } /** * @dev transfers the anchor ownership * the new owner needs to accept the transfer * can only be called by the converter upgrder while the upgrader is the owner * note that prior to version 28, you should use 'transferAnchorOwnership' instead * * @param _newOwner new token owner */ function transferAnchorOwnership(address _newOwner) public override ownerOnly only(CONVERTER_UPGRADER) { anchor.transferOwnership(_newOwner); } /** * @dev accepts ownership of the anchor after an ownership transfer * most converters are also activated as soon as they accept the anchor ownership * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public virtual override ownerOnly { // verify the the converter has at least one reserve require(reserveTokenCount() > 0, "ERR_INVALID_RESERVE_COUNT"); anchor.acceptOwnership(); syncReserveBalances(); } /** * @dev updates the current conversion fee * can only be called by the contract owner * * @param _conversionFee new conversion fee, represented in ppm */ function setConversionFee(uint32 _conversionFee) public override ownerOnly { require(_conversionFee <= maxConversionFee, "ERR_INVALID_CONVERSION_FEE"); emit ConversionFeeUpdate(conversionFee, _conversionFee); conversionFee = _conversionFee; } /** * @dev withdraws tokens held by the converter and sends them to an account * can only be called by the owner * note that reserve tokens can only be withdrawn by the owner while the converter is inactive * unless the owner is the converter upgrader contract * * @param _token ERC20 token contract address * @param _to account to receive the new amount * @param _amount amount to withdraw */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public override(IConverter, TokenHolder) protected ownerOnly { address converterUpgrader = addressOf(CONVERTER_UPGRADER); // if the token is not a reserve token, allow withdrawal // otherwise verify that the converter is inactive or that the owner is the upgrader contract require(!reserves[_token].isSet || !isActive() || owner == converterUpgrader, "ERR_ACCESS_DENIED"); super.withdrawTokens(_token, _to, _amount); // if the token is a reserve token, sync the reserve balance if (reserves[_token].isSet) syncReserveBalance(_token); } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new converter after the upgrade */ function upgrade() public ownerOnly { IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER)); // trigger de-activation event emit Activation(converterType(), anchor, false); transferOwnership(address(converterUpgrader)); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev returns the number of reserve tokens defined * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view returns (uint16) { return uint16(reserveTokens.length); } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public virtual override ownerOnly inactive validAddress(address(_token)) notThis(address(_token)) validReserveWeight(_weight) { // validate input require(address(_token) != address(anchor) && !reserves[_token].isSet, "ERR_INVALID_RESERVE"); require(_weight <= PPM_RESOLUTION - reserveRatio, "ERR_INVALID_RESERVE_WEIGHT"); require(reserveTokenCount() < uint16(-1), "ERR_INVALID_RESERVE_COUNT"); Reserve storage newReserve = reserves[_token]; newReserve.balance = 0; newReserve.weight = _weight; newReserve.isSet = true; reserveTokens.push(_token); reserveRatio += _weight; } /** * @dev returns the reserve's weight * added in version 28 * * @param _reserveToken reserve token contract address * * @return reserve weight */ function reserveWeight(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint32) { return reserves[_reserveToken].weight; } /** * @dev returns the reserve's balance * note that prior to version 17, you should use 'getConnectorBalance' instead * * @param _reserveToken reserve token contract address * * @return reserve balance */ function reserveBalance(IERC20Token _reserveToken) public override view validReserve(_reserveToken) returns (uint256) { return reserves[_reserveToken].balance; } /** * @dev checks whether or not the converter has an ETH reserve * * @return true if the converter has an ETH reserve, false otherwise */ function hasETHReserve() public view returns (bool) { return reserves[ETH_RESERVE_ADDRESS].isSet; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function convert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) //injected LOCKED ETHER public override payable protected only(BANCOR_NETWORK) returns (uint256) { // validate input require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); // if a whitelist is set, verify that both and trader and the beneficiary are whitelisted require(address(conversionWhitelist) == address(0) || (conversionWhitelist.isWhitelisted(_trader) && conversionWhitelist.isWhitelisted(_beneficiary)), "ERR_NOT_WHITELISTED"); return doConvert(_sourceToken, _targetToken, _amount, _trader, _beneficiary); } /** * @dev converts a specific amount of source tokens to target tokens * called by ConverterBase and allows the inherited contracts to implement custom conversion logic * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal virtual returns (uint256); /** * @dev returns the conversion fee for a given target amount * * @param _targetAmount target amount * * @return conversion fee */ function calculateFee(uint256 _targetAmount) internal view returns (uint256) { return _targetAmount.mul(conversionFee).div(PPM_RESOLUTION); } /** * @dev syncs the stored reserve balance for a given reserve with the real reserve balance * * @param _reserveToken address of the reserve token */ function syncReserveBalance(IERC20Token _reserveToken) internal validReserve(_reserveToken) { if (_reserveToken == ETH_RESERVE_ADDRESS) reserves[_reserveToken].balance = address(this).balance; else reserves[_reserveToken].balance = _reserveToken.balanceOf(address(this)); } /** * @dev syncs all stored reserve balances */ function syncReserveBalances() internal { uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) syncReserveBalance(reserveTokens[i]); } /** * @dev helper, dispatches the Conversion event * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _trader address of the caller who executed the conversion * @param _amount amount purchased/sold (in the source token) * @param _returnAmount amount returned (in the target token) */ function dispatchConversionEvent( IERC20Token _sourceToken, IERC20Token _targetToken, address _trader, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) internal { // fee amount is converted to 255 bits - // negative amount means the fee is taken from the source token, positive amount means its taken from the target token // currently the fee is always taken from the target token // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow assert(_feeAmount < 2 ** 255); emit Conversion(_sourceToken, _targetToken, _trader, _amount, _returnAmount, int256(_feeAmount)); } /** * @dev deprecated since version 28, backward compatibility - use only for earlier versions */ function token() public view override returns (IConverterAnchor) { return anchor; } /** * @dev deprecated, backward compatibility */ function transferTokenOwnership(address _newOwner) public override ownerOnly { transferAnchorOwnership(_newOwner); } /** * @dev deprecated, backward compatibility */ function acceptTokenOwnership() public override ownerOnly { acceptAnchorOwnership(); } /** * @dev deprecated, backward compatibility */ function connectors(IERC20Token _address) public view override returns (uint256, uint32, bool, bool, bool) { Reserve memory reserve = reserves[_address]; return(reserve.balance, reserve.weight, false, false, reserve.isSet); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 _index) public view override returns (IERC20Token) { return ConverterBase.reserveTokens[_index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() public view override returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IERC20Token _connectorToken) public view override returns (uint256) { return reserveBalance(_connectorToken); } /** * @dev deprecated, backward compatibility */ function getReturn(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view returns (uint256, uint256) { return targetAmountAndFee(_sourceToken, _targetToken, _amount); } } // File: solidity/contracts/converter/LiquidityPoolConverter.sol pragma solidity 0.6.12; /** * @dev Liquidity Pool Converter * * The liquidity pool converter is the base contract for specific types of converters that * manage liquidity pools. * * Liquidity pools have 2 reserves or more and they allow converting between them. * * Note that TokenRateUpdate events are dispatched for pool tokens as well. * The pool token is the first token in the event in that case. */ abstract contract LiquidityPoolConverter is ConverterBase { /** * @dev triggered after liquidity is added * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityAdded( address indexed _provider, IERC20Token indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply ); /** * @dev triggered after liquidity is removed * * @param _provider liquidity provider * @param _reserveToken reserve token address * @param _amount reserve token amount * @param _newBalance reserve token new balance * @param _newSupply pool token new supply */ event LiquidityRemoved( address indexed _provider, IERC20Token indexed _reserveToken, uint256 _amount, uint256 _newBalance, uint256 _newSupply ); /** * @dev initializes a new LiquidityPoolConverter instance * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee ) ConverterBase(_anchor, _registry, _maxConversionFee) internal { } /** * @dev accepts ownership of the anchor after an ownership transfer * also activates the converter * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public virtual override { // verify that the converter has at least 2 reserves require(reserveTokenCount() > 1, "ERR_INVALID_RESERVE_COUNT"); super.acceptAnchorOwnership(); } } // File: solidity/contracts/token/interfaces/IDSToken.sol pragma solidity 0.6.12; /* DSToken interface */ interface IDSToken is IConverterAnchor, IERC20Token { function issue(address _to, uint256 _amount) external; function destroy(address _from, uint256 _amount) external; } // File: solidity/contracts/utility/Math.sol pragma solidity 0.6.12; /** * @dev Library for complex math operations */ library Math { using SafeMath for uint256; /** * @dev returns the largest integer smaller than or equal to the square root of a positive integer * * @param _num a positive integer * * @return the largest integer smaller than or equal to the square root of the positive integer */ function floorSqrt(uint256 _num) internal pure returns (uint256) { uint256 x = _num / 2 + 1; uint256 y = (x + _num / x) / 2; while (x > y) { x = y; y = (x + _num / x) / 2; } return x; } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) { if (_n > _max || _d > _max) return normalizedRatio(_n, _d, _max); return (_n, _d); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { if (_a == _b) return (_scale / 2, _scale / 2); if (_a < _b) return accurateRatio(_a, _b, _scale); (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b". */ function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * _scale, _a.add(_b)); uint256 y = _scale - x; return (x, y); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + _n % _d / (_d - _d / 2); } /** * @dev returns the average number of decimal digits in a given list of positive integers * * @param _values list of positive integers * * @return the average number of decimal digits in the given list of positive integers */ function geometricMean(uint256[] memory _values) internal pure returns (uint256) { uint256 numOfDigits = 0; uint256 length = _values.length; for (uint256 i = 0; i < length; i++) numOfDigits += decimalLength(_values[i]); return uint256(10) ** (roundDivUnsafe(numOfDigits, length) - 1); } /** * @dev returns the number of decimal digits in a given positive integer * * @param _x positive integer * * @return the number of decimal digits in the given positive integer */ function decimalLength(uint256 _x) internal pure returns (uint256) { uint256 y = 0; for (uint256 x = _x; x > 0; x /= 10) y++; return y; } /** * @dev returns the nearest integer to a given quotient * the computation is overflow-safe assuming that the input is sufficiently small * * @param _n quotient numerator * @param _d quotient denominator * * @return the nearest integer to the given quotient */ function roundDivUnsafe(uint256 _n, uint256 _d) internal pure returns (uint256) { return (_n + _d / 2) / _d; } } // File: solidity/contracts/utility/Types.sol pragma solidity 0.6.12; /** * @dev Provides types that can be used by various contracts */ struct Fraction { uint256 n; // numerator uint256 d; // denominator } // File: solidity/contracts/converter/types/liquidity-pool-v1/LiquidityPoolV1Converter.sol pragma solidity 0.6.12; /** * @dev Liquidity Pool v1 Converter * * The liquidity pool v1 converter is a specialized version of a converter that manages * a classic bancor liquidity pool. * * Even though pools can have many reserves, the standard pool configuration * is 2 reserves with 50%/50% weights. */ contract LiquidityPoolV1Converter is LiquidityPoolConverter { using Math for *; IEtherToken internal etherToken = IEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30; // the period of time taken into account when calculating the recent averate rate uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes; // true if the pool is a 2 reserves / 50%/50% weights pool, false otherwise bool public isStandardPool = false; // only used in standard pools Fraction public prevAverageRate; // average rate after the previous conversion (1 reserve token 0 in reserve token 1 units) uint256 public prevAverageRateUpdateTime; // last time when the previous rate was updated (in seconds) /** * @dev triggered after a conversion with new price data * deprecated, use `TokenRateUpdate` from version 28 and up * * @param _connectorToken reserve token * @param _tokenSupply pool token supply * @param _connectorBalance reserve balance * @param _connectorWeight reserve weight */ event PriceDataUpdate( IERC20Token indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); /** * @dev initializes a new LiquidityPoolV1Converter instance * * @param _token pool token governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor( IDSToken _token, IContractRegistry _registry, uint32 _maxConversionFee ) LiquidityPoolConverter(_token, _registry, _maxConversionFee) public { } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public pure override returns (uint16) { return 1; } /** * @dev accepts ownership of the anchor after an ownership transfer * also activates the converter * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public override ownerOnly { super.acceptAnchorOwnership(); emit Activation(converterType(), anchor, true); } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly { super.addReserve(_token, _weight); isStandardPool = reserveTokens.length == 2 && reserves[reserveTokens[0]].weight == PPM_RESOLUTION / 2 && reserves[reserveTokens[1]].weight == PPM_RESOLUTION / 2; } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public view override active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256, uint256) { // validate input require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); uint256 amount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount( reserveBalance(_sourceToken), reserves[_sourceToken].weight, reserveBalance(_targetToken), reserves[_targetToken].weight, _amount ); // return the amount minus the conversion fee and the conversion fee uint256 fee = calculateFee(amount); return (amount - fee, fee); } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override returns (uint256) { // update the recent average rate if (isStandardPool && prevAverageRateUpdateTime < time()) { prevAverageRate = recentAverageRate(); prevAverageRateUpdateTime = time(); } // get expected target amount and fee (uint256 amount, uint256 fee) = targetAmountAndFee(_sourceToken, _targetToken, _amount); // ensure that the trade gives something in return require(amount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance assert(amount < reserveBalance(_targetToken)); // ensure that the input amount was already deposited if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserveBalance(_sourceToken)) >= _amount, "ERR_INVALID_AMOUNT"); // sync the reserve balances syncReserveBalance(_sourceToken); reserves[_targetToken].balance = reserves[_targetToken].balance.sub(amount); // transfer funds to the beneficiary in the to reserve token if (_targetToken == ETH_RESERVE_ADDRESS) _beneficiary.transfer(0); else safeTransfer(_targetToken, _beneficiary, amount); // dispatch the conversion event dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee); // dispatch rate updates dispatchTokenRateUpdateEvents(_sourceToken, _targetToken); return amount; } /** * @dev returns the recent average rate of 1 `_token` in the other reserve token units * note that the rate can only be queried for reserves in a standard pool * * @param _token token to get the rate for * @return recent average rate between the reserves (numerator) * @return recent average rate between the reserves (denominator) */ function recentAverageRate(IERC20Token _token) external view returns (uint256, uint256) { // verify that the pool is standard require(isStandardPool, "ERR_NON_STANDARD_POOL"); // get the recent average rate of reserve 0 Fraction memory rate = recentAverageRate(); if (_token == reserveTokens[0]) { return (rate.n, rate.d); } return (rate.d, rate.n); } /** * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units * * @return recent average rate between the reserves */ function recentAverageRate() internal view returns (Fraction memory) { // get the elapsed time since the previous average rate was calculated uint256 timeElapsed = time() - prevAverageRateUpdateTime; // if the previous average rate was calculated in the current block, return it if (timeElapsed == 0) { return prevAverageRate; } // get the current rate between the reserves uint256 currentRateN = reserves[reserveTokens[1]].balance; uint256 currentRateD = reserves[reserveTokens[0]].balance; // if the previous average rate was calculated a while ago, the average rate is equal to the current rate if (timeElapsed >= AVERAGE_RATE_PERIOD) { return Fraction({ n: currentRateN, d: currentRateD }); } // given N as the sampling window, the new rate is calculated according to the following formula: // newRate = prevAverageRate + timeElapsed * [currentRate - prevAverageRate] / N // calculate the numerator and the denumerator of the new rate Fraction memory prevAverage = prevAverageRate; uint256 x = prevAverage.d.mul(currentRateN); uint256 y = prevAverage.n.mul(currentRateD); // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath: uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed)); uint256 newRateD = prevAverage.d.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = Math.reducedRatio(newRateN, newRateD, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction({ n: newRateN, d: newRateD }); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * note that prior to version 28, you should use 'fund' instead * * @param _reserveTokens address of each reserve token * @param _reserveAmounts amount of each reserve token * @param _minReturn token minimum return-amount * * @return amount of pool tokens issued */ function addLiquidity(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _minReturn) //injected LOCKED ETHER public payable protected active returns (uint256) { // verify the user input verifyLiquidityInput(_reserveTokens, _reserveAmounts, _minReturn); // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH for (uint256 i = 0; i < _reserveTokens.length; i++) if (_reserveTokens[i] == ETH_RESERVE_ADDRESS) require(_reserveAmounts[i] == msg.value, "ERR_ETH_AMOUNT_MISMATCH"); // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH if (msg.value > 0) { require(reserves[ETH_RESERVE_ADDRESS].isSet, "ERR_NO_ETH_RESERVE"); } // get the total supply uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); // transfer from the user an equally-worth amount of each one of the reserve tokens uint256 amount = addLiquidityToPool(_reserveTokens, _reserveAmounts, totalSupply); // verify that the equivalent amount of tokens is equal to or larger than the user's expectation require(amount >= _minReturn, "ERR_RETURN_TOO_LOW"); // issue the tokens to the user IDSToken(address(anchor)).issue(msg.sender, amount); // return the amount of pool tokens issued return amount; } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * note that prior to version 28, you should use 'liquidate' instead * * @param _amount token amount * @param _reserveTokens address of each reserve token * @param _reserveMinReturnAmounts minimum return-amount of each reserve token * * @return the amount of each reserve token granted for the given amount of pool tokens */ function removeLiquidity(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts) public protected active returns (uint256[] memory) { // verify the user input verifyLiquidityInput(_reserveTokens, _reserveMinReturnAmounts, _amount); // get the total supply BEFORE destroying the user tokens uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); // destroy the user tokens IDSToken(address(anchor)).destroy(msg.sender, _amount); // transfer to the user an equivalent amount of each one of the reserve tokens return removeLiquidityFromPool(_reserveTokens, _reserveMinReturnAmounts, totalSupply, _amount); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * for example, if the caller increases the supply by 10%, * then it will cost an amount equal to 10% of each reserve token balance * note that starting from version 28, you should use 'addLiquidity' instead * * @param _amount amount to increase the supply by (in the pool token) * * @return amount of pool tokens issued */ function fund(uint256 _amount) //injected LOCKED ETHER public payable protected returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); uint256 supply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); // iterate through the reserve tokens and transfer a percentage equal to the weight between // _amount and the total supply in each reserve from the caller to the converter uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { IERC20Token reserveToken = reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(supply, rsvBalance, reserveRatio, _amount); // transfer funds from the caller in the reserve token if (reserveToken == ETH_RESERVE_ADDRESS) { if (msg.value > reserveAmount) { msg.sender.transfer(0); } else if (msg.value < reserveAmount) { require(msg.value == 0, "ERR_INVALID_ETH_VALUE"); safeTransferFrom(etherToken, msg.sender, address(this), reserveAmount); etherToken.withdraw(reserveAmount); } } else { safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); } // sync the reserve balance uint256 newReserveBalance = rsvBalance.add(reserveAmount); reserves[reserveToken].balance = newReserveBalance; uint256 newPoolTokenSupply = supply.add(_amount); // dispatch liquidity update for the pool token/reserve emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } // issue new funds to the caller in the pool token IDSToken(address(anchor)).issue(msg.sender, _amount); // return the amount of pool tokens issued return _amount; } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * for example, if the holder sells 10% of the supply, * then they will receive 10% of each reserve token balance in return * note that starting from version 28, you should use 'removeLiquidity' instead * * @param _amount amount to liquidate (in the pool token) * * @return the amount of each reserve token granted for the given amount of pool tokens */ function liquidate(uint256 _amount) public protected returns (uint256[] memory) { require(_amount > 0, "ERR_ZERO_AMOUNT"); uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IDSToken(address(anchor)).destroy(msg.sender, _amount); uint256[] memory reserveMinReturnAmounts = new uint256[](reserveTokens.length); for (uint256 i = 0; i < reserveMinReturnAmounts.length; i++) reserveMinReturnAmounts[i] = 1; return removeLiquidityFromPool(reserveTokens, reserveMinReturnAmounts, totalSupply, _amount); } /** * @dev given the amount of one of the reserve tokens to add liquidity of, * returns the required amount of each one of the other reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param _reserveTokens address of each reserve token * @param _reserveTokenIndex index of the relevant reserve token * @param _reserveAmount amount of the relevant reserve token * * @return the required amount of each one of the reserve tokens */ function addLiquidityCost(IERC20Token[] memory _reserveTokens, uint256 _reserveTokenIndex, uint256 _reserveAmount) public view returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = formula.fundSupplyAmount(totalSupply, reserves[_reserveTokens[_reserveTokenIndex]].balance, reserveRatio, _reserveAmount); for (uint256 i = 0; i < reserveAmounts.length; i++) reserveAmounts[i] = formula.fundCost(totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, amount); return reserveAmounts; } /** * @dev given the amount of one of the reserve tokens to add liquidity of, * returns the amount of pool tokens entitled for it * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param _reserveToken address of the reserve token * @param _reserveAmount amount of the reserve token * * @return the amount of pool tokens entitled */ function addLiquidityReturn(IERC20Token _reserveToken, uint256 _reserveAmount) public view returns (uint256) { uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); return formula.fundSupplyAmount(totalSupply, reserves[_reserveToken].balance, reserveRatio, _reserveAmount); } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param _amount amount of pool tokens * @param _reserveTokens address of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReturn(uint256 _amount, IERC20Token[] memory _reserveTokens) public view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(anchor)).totalSupply(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); return removeLiquidityReserveAmounts(_amount, _reserveTokens, totalSupply, formula); } /** * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens * we take this input in order to allow specifying the corresponding reserve amounts in any order * * @param _reserveTokens array of reserve tokens * @param _reserveAmounts array of reserve amounts * @param _amount token amount */ function verifyLiquidityInput(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _amount) private view { uint256 i; uint256 j; uint256 length = reserveTokens.length; require(length == _reserveTokens.length, "ERR_INVALID_RESERVE"); require(length == _reserveAmounts.length, "ERR_INVALID_AMOUNT"); for (i = 0; i < length; i++) { // verify that every input reserve token is included in the reserve tokens require(reserves[_reserveTokens[i]].isSet, "ERR_INVALID_RESERVE"); for (j = 0; j < length; j++) { if (reserveTokens[i] == _reserveTokens[j]) break; } // verify that every reserve token is included in the input reserve tokens require(j < length, "ERR_INVALID_RESERVE"); // verify that every input reserve token amount is larger than zero require(_reserveAmounts[i] > 0, "ERR_INVALID_AMOUNT"); } // verify that the input token amount is larger than zero require(_amount > 0, "ERR_ZERO_AMOUNT"); } /** * @dev adds liquidity (reserve) to the pool * * @param _reserveTokens address of each reserve token * @param _reserveAmounts amount of each reserve token * @param _totalSupply token total supply * * @return amount of pool tokens issued */ function addLiquidityToPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply) private returns (uint256) { if (_totalSupply == 0) return addLiquidityToEmptyPool(_reserveTokens, _reserveAmounts); return addLiquidityToNonEmptyPool(_reserveTokens, _reserveAmounts, _totalSupply); } /** * @dev adds liquidity (reserve) to the pool when it's empty * * @param _reserveTokens address of each reserve token * @param _reserveAmounts amount of each reserve token * * @return amount of pool tokens issued */ function addLiquidityToEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private returns (uint256) { // calculate the geometric-mean of the reserve amounts approved by the user uint256 amount = Math.geometricMean(_reserveAmounts); // transfer each one of the reserve amounts from the user to the pool for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = _reserveAmounts[i]; if (reserveToken != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); reserves[reserveToken].balance = reserveAmount; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, reserveAmount, amount); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(amount, reserveToken, reserveAmount, reserves[reserveToken].weight); } // return the amount of pool tokens issued return amount; } /** * @dev adds liquidity (reserve) to the pool when it's not empty * * @param _reserveTokens address of each reserve token * @param _reserveAmounts amount of each reserve token * @param _totalSupply token total supply * * @return amount of pool tokens issued */ function addLiquidityToNonEmptyPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts, uint256 _totalSupply) private returns (uint256) { syncReserveBalances(); reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 amount = getMinShare(formula, _totalSupply, _reserveTokens, _reserveAmounts); uint256 newPoolTokenSupply = _totalSupply.add(amount); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 rsvBalance = reserves[reserveToken].balance; uint256 reserveAmount = formula.fundCost(_totalSupply, rsvBalance, reserveRatio, amount); require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= _reserveAmounts[i]); // transfer each one of the reserve amounts from the user to the pool if (reserveToken != ETH_RESERVE_ADDRESS) // ETH has already been transferred as part of the transaction safeTransferFrom(reserveToken, msg.sender, address(this), reserveAmount); else if (_reserveAmounts[i] > reserveAmount) // transfer the extra amount of ETH back to the user msg.sender.transfer(0); uint256 newReserveBalance = rsvBalance.add(reserveAmount); reserves[reserveToken].balance = newReserveBalance; emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } // return the amount of pool tokens issued return amount; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param _amount amount of pool tokens * @param _reserveTokens address of each reserve token * @param _totalSupply token total supply * @param _formula formula contract * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReserveAmounts(uint256 _amount, IERC20Token[] memory _reserveTokens, uint256 _totalSupply, IBancorFormula _formula) private view returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](_reserveTokens.length); for (uint256 i = 0; i < reserveAmounts.length; i++) reserveAmounts[i] = _formula.liquidateReserveAmount(_totalSupply, reserves[_reserveTokens[i]].balance, reserveRatio, _amount); return reserveAmounts; } /** * @dev removes liquidity (reserve) from the pool * * @param _reserveTokens address of each reserve token * @param _reserveMinReturnAmounts minimum return-amount of each reserve token * @param _totalSupply token total supply * @param _amount token amount * * @return the amount of each reserve token granted for the given amount of pool tokens */ function removeLiquidityFromPool(IERC20Token[] memory _reserveTokens, uint256[] memory _reserveMinReturnAmounts, uint256 _totalSupply, uint256 _amount) private returns (uint256[] memory) { syncReserveBalances(); IBancorFormula formula = IBancorFormula(addressOf(BANCOR_FORMULA)); uint256 newPoolTokenSupply = _totalSupply.sub(_amount); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(_amount, _reserveTokens, _totalSupply, formula); for (uint256 i = 0; i < _reserveTokens.length; i++) { IERC20Token reserveToken = _reserveTokens[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= _reserveMinReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); uint256 newReserveBalance = reserves[reserveToken].balance.sub(reserveAmount); reserves[reserveToken].balance = newReserveBalance; // transfer each one of the reserve amounts from the pool to the user if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(0); else safeTransfer(reserveToken, msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(newPoolTokenSupply, reserveToken, newReserveBalance, reserves[reserveToken].weight); } // return the amount of each reserve token granted for the given amount of pool tokens return reserveAmounts; } function getMinShare(IBancorFormula formula, uint256 _totalSupply, IERC20Token[] memory _reserveTokens, uint256[] memory _reserveAmounts) private view returns (uint256) { uint256 minIndex = 0; for (uint256 i = 1; i < _reserveTokens.length; i++) { if (_reserveAmounts[i].mul(reserves[_reserveTokens[minIndex]].balance) < _reserveAmounts[minIndex].mul(reserves[_reserveTokens[i]].balance)) minIndex = i; } return formula.fundSupplyAmount(_totalSupply, reserves[_reserveTokens[minIndex]].balance, reserveRatio, _reserveAmounts[minIndex]); } /** * @dev dispatches token rate update events for the reserve tokens and the pool token * * @param _sourceToken address of the source reserve token * @param _targetToken address of the target reserve token */ function dispatchTokenRateUpdateEvents(IERC20Token _sourceToken, IERC20Token _targetToken) private { uint256 poolTokenSupply = IDSToken(address(anchor)).totalSupply(); uint256 sourceReserveBalance = reserveBalance(_sourceToken); uint256 targetReserveBalance = reserveBalance(_targetToken); uint32 sourceReserveWeight = reserves[_sourceToken].weight; uint32 targetReserveWeight = reserves[_targetToken].weight; // dispatch token rate update event for the reserve tokens uint256 rateN = targetReserveBalance.mul(sourceReserveWeight); uint256 rateD = sourceReserveBalance.mul(targetReserveWeight); emit TokenRateUpdate(_sourceToken, _targetToken, rateN, rateD); // dispatch token rate update events for the pool token dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _sourceToken, sourceReserveBalance, sourceReserveWeight); dispatchPoolTokenRateUpdateEvent(poolTokenSupply, _targetToken, targetReserveBalance, targetReserveWeight); // dispatch price data update events (deprecated events) emit PriceDataUpdate(_sourceToken, poolTokenSupply, sourceReserveBalance, sourceReserveWeight); emit PriceDataUpdate(_targetToken, poolTokenSupply, targetReserveBalance, targetReserveWeight); } /** * @dev dispatches token rate update event for the pool token * * @param _poolTokenSupply total pool token supply * @param _reserveToken address of the reserve token * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight */ function dispatchPoolTokenRateUpdateEvent(uint256 _poolTokenSupply, IERC20Token _reserveToken, uint256 _reserveBalance, uint32 _reserveWeight) private { emit TokenRateUpdate(IDSToken(address(anchor)), _reserveToken, _reserveBalance.mul(PPM_RESOLUTION), _poolTokenSupply.mul(_reserveWeight)); } /** * @dev returns the current time * utility to allow overrides for tests */ function time() internal view virtual returns (uint256) { return now; } } // File: solidity/contracts/converter/interfaces/ITypedConverterFactory.sol pragma solidity 0.6.12; /* Typed Converter Factory interface */ interface ITypedConverterFactory { function converterType() external pure returns (uint16); function createConverter(IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee) external returns (IConverter); } // File: solidity/contracts/converter/types/liquidity-pool-v1/LiquidityPoolV1ConverterFactory.sol pragma solidity 0.6.12; /* LiquidityPoolV1Converter Factory */ contract LiquidityPoolV1ConverterFactory is ITypedConverterFactory { /** * @dev returns the converter type the factory is associated with * * @return converter type */ function converterType() external pure override returns (uint16) { return 1; } /** * @dev creates a new converter with the given arguments and transfers * the ownership to the caller * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm * * @return a new converter */ function createConverter(IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee) external virtual override returns (IConverter) { IConverter converter = new LiquidityPoolV1Converter(IDSToken(address(_anchor)), _registry, _maxConversionFee); converter.transferOwnership(msg.sender); return converter; } }
checks whether or not the converter has an ETH reserve return true if the converter has an ETH reserve, false otherwise/
function hasETHReserve() public view returns (bool) { return reserves[ETH_RESERVE_ADDRESS].isSet; }
12,987,263
/** *Submitted for verification at Etherscan.io on 2020-05-15 */ // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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/common/implementation/FixedPoint.sol pragma solidity ^0.6.0; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // Can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } // File: contracts/common/interfaces/ExpandedIERC20.sol pragma solidity ^0.6.0; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); } // File: contracts/oracle/interfaces/OracleInterface.sol pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ interface OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) external; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) external view returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) external view returns (int256); } // File: contracts/oracle/interfaces/IdentifierWhitelistInterface.sol pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // File: contracts/oracle/interfaces/AdministrateeInterface.sol pragma solidity ^0.6.0; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; } // File: contracts/oracle/implementation/Constants.sol pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/common/implementation/MultiRole.sol pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // File: contracts/common/implementation/ExpandedERC20.sol pragma solidity ^0.6.0; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } } // File: contracts/common/implementation/Lockable.sol pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: contracts/financial-templates/common/SyntheticToken.sol pragma solidity ^0.6.0; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // File: contracts/financial-templates/common/TokenFactory.sol pragma solidity ^0.6.0; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // File: contracts/common/implementation/Timer.sol pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // File: contracts/common/implementation/Testable.sol pragma solidity ^0.6.0; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // File: contracts/oracle/interfaces/StoreInterface.sol pragma solidity ^0.6.0; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // File: contracts/oracle/interfaces/FinderInterface.sol pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // File: contracts/financial-templates/common/FeePayer.sol pragma solidity ^0.6.0; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees { payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) nonReentrant() { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { StoreInterface store = _getStore(); uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral from which to pay fees. if (collateralPool.isEqual(0)) { return totalPaid; } // Exit early if fees were already paid during this block. if (lastPaymentTime == time) { return totalPaid; } (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) = store.computeRegularFee( lastPaymentTime, time, collateralPool ); lastPaymentTime = time; totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return totalPaid; } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corrution denominated in collateral currency. */ function pfc() public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. require(collateralPool.isGreaterThan(amount), "Final fee is more than PfC"); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _pfc() internal virtual view returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // File: contracts/financial-templates/expiring-multiparty/PricelessPositionManager.sol pragma solidity ^0.6.0; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer, AdministrateeInterface { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _syntheticName name for the token contract that will be deployed. * @param _syntheticSymbol symbol for the token contract that will be deployed. * @param _tokenFactoryAddress deployed UMA token factory to create the synthetic token. * @param _minSponsorTokens minimum amount of collateral that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, string memory _syntheticName, string memory _syntheticSymbol, address _tokenFactoryAddress, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime(), "Invalid expiration in future"); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; TokenFactory tf = TokenFactory(_tokenFactoryAddress); tokenCurrency = tf.createToken(_syntheticName, _syntheticSymbol, 18); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0, "Pending transfer"); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ), "Sponsor already has position" ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime(), "Invalid transfer request" ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0, "No pending transfer"); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the witdrawl. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)), "Invalid collateral amount" ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp, "Request expires post-expiry"); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { require(_checkCollateralization(collateralAmount, numTokens), "CR below GCR"); PositionData storage positionData = positions[msg.sender]; require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue), "Minting synthetic tokens failed"); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePrice(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan( positionCollateral ) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral ); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // The final fee for this request is paid out of the contract rather than by the caller. _payFinalFees(address(this), _computeFinalFees()); _requestOraclePrice(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress(), "Caller not Governor"); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePrice(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getFeeAdjustedCollateral(positions[sponsor].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal virtual override view returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio( _getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding ); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } } // File: contracts/financial-templates/expiring-multiparty/Liquidatable.sol pragma solidity ^0.6.0; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, PreDispute, PendingDispute, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address finderAddress; address tokenFactoryAddress; address timerAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPct; FixedPoint.Unsigned sponsorDisputeRewardPct; FixedPoint.Unsigned disputerDisputeRewardPct; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPct; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPct; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPct; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn(address indexed caller, uint256 withdrawalAmount, Status indexed liquidationStatus); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.finderAddress, params.priceFeedIdentifier, params.syntheticName, params.syntheticSymbol, params.tokenFactoryAddress, params.minSponsorTokens, params.timerAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1), "CR is more than 100%"); require( params.sponsorDisputeRewardPct.add(params.disputerDisputeRewardPct).isLessThan(1), "Rewards are more than 100%" ); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPct = params.disputeBondPct; sponsorDisputeRewardPct = params.sponsorDisputeRewardPct; disputerDisputeRewardPct = params.disputerDisputeRewardPct; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul( ratio ); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.PreDispute, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPct` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPct).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.PendingDispute; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * the sponsor, liquidator, and/or disputer can call this method to receive payments. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * Once all collateral is withdrawn, delete the liquidation data. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return amountWithdrawn the total amount of underlying returned from the liquidation. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (msg.sender == liquidation.disputer) || (msg.sender == liquidation.liquidator) || (msg.sender == liquidation.sponsor), "Caller cannot withdraw rewards" ); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory tokenRedemptionValue = liquidation .tokensOutstanding .mul(liquidation.settlementPrice) .mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPct.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPct); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation can withdraw different amounts. // Once a caller has been paid their address deleted from the struct. // This prevents them from being paid multiple from times the same liquidation. FixedPoint.Unsigned memory withdrawalAmount = FixedPoint.fromUnscaledUint(0); if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users can withdraw from the contract. if (msg.sender == liquidation.disputer) { // Pay DISPUTER: disputer reward + dispute bond + returned final fee FixedPoint.Unsigned memory payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); withdrawalAmount = withdrawalAmount.add(payToDisputer); delete liquidation.disputer; } if (msg.sender == liquidation.sponsor) { // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward FixedPoint.Unsigned memory remainingCollateral = collateral.sub(tokenRedemptionValue); FixedPoint.Unsigned memory payToSponsor = sponsorDisputeReward.add(remainingCollateral); withdrawalAmount = withdrawalAmount.add(payToSponsor); delete liquidation.sponsor; } if (msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePct+disputerDisputePct) >= 0 in // the constructor when these params are set. FixedPoint.Unsigned memory payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub( disputerDisputeReward ); withdrawalAmount = withdrawalAmount.add(payToLiquidator); delete liquidation.liquidator; } // Free up space once all collateral is withdrawn by removing the liquidation object from the array. if ( liquidation.disputer == address(0) && liquidation.sponsor == address(0) && liquidation.liquidator == address(0) ) { delete liquidations[sponsor][liquidationId]; } // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee withdrawalAmount = collateral.add(disputeBondAmount).add(finalFee); delete liquidations[sponsor][liquidationId]; // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.PreDispute && msg.sender == liquidation.liquidator) { // Pay LIQUIDATOR: collateral + returned final fee withdrawalAmount = collateral.add(finalFee); delete liquidations[sponsor][liquidationId]; } require(withdrawalAmount.isGreaterThan(0), "Invalid withdrawal amount"); // Decrease the total collateral held in liquidatable by the amount withdrawn. amountWithdrawn = _removeCollateral(rawLiquidationCollateral, withdrawalAmount); emit LiquidationWithdrawn(msg.sender, amountWithdrawn.rawValue, liquidation.state); // Transfer amount withdrawn from this contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); return amountWithdrawn; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the PendingDispute state. If not, it will immediately return. // If the liquidation is in the PendingDispute state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == PendingDispute and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.PendingDispute) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul( liquidation.settlementPrice ); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal override view returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.PreDispute), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.PreDispute) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.PreDispute)), "Liquidation not withdrawable" ); } } // File: contracts/financial-templates/expiring-multiparty/ExpiringMultiParty.sol pragma solidity ^0.6.0; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // File: contracts/financial-templates/expiring-multiparty/ExpiringMultiPartyLib.sol pragma solidity ^0.6.0; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } }
Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral in order to account for precision loss. This contract must be approved to spend at least `numTokens` of `tokenCurrency`. numTokens is the number of tokens to be burnt for a commensurate amount of collateral. return amountWithdrawn The actual amount of collateral withdrawn./ If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. Decrement the sponsor's collateral and global collateral amounts. Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. Update the totalTokensOutstanding after redemption.
function redeem(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding), "Invalid token amount"); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul( _getFeeAdjustedCollateral(positionData.rawCollateral) ); if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); }
7,794,985
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./SafeMath.sol"; import "./HoldefiPausableOwnable.sol"; import "./HoldefiCollaterals.sol"; /// @notice File: contracts/HoldefiPrices.sol interface HoldefiPricesInterface { function getAssetValueFromAmount(address asset, uint256 amount) external view returns(uint256 value); function getAssetAmountFromValue(address asset, uint256 value) external view returns(uint256 amount); } /// @notice File: contracts/HoldefiSettings.sol interface HoldefiSettingsInterface { /// @notice Markets Features struct MarketSettings { bool isExist; bool isActive; uint256 borrowRate; uint256 borrowRateUpdateTime; uint256 suppliersShareRate; uint256 suppliersShareRateUpdateTime; uint256 promotionRate; } /// @notice Collateral Features struct CollateralSettings { bool isExist; bool isActive; uint256 valueToLoanRate; uint256 VTLUpdateTime; uint256 penaltyRate; uint256 penaltyUpdateTime; uint256 bonusRate; } function getInterests(address market) external view returns (uint256 borrowRate, uint256 supplyRateBase, uint256 promotionRate); function resetPromotionRate (address market) external; function getMarketsList() external view returns(address[] memory marketsList); function marketAssets(address market) external view returns(MarketSettings memory); function collateralAssets(address collateral) external view returns(CollateralSettings memory); } /// @title Main Holdefi contract /// @author Holdefi Team /// @dev The address of ETH considered as 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE /// @dev All indexes are scaled by (secondsPerYear * rateDecimals) /// @dev All values are based ETH price considered 1 and all values decimals considered 30 contract Holdefi is HoldefiPausableOwnable { using SafeMath for uint256; /// @notice Markets are assets can be supplied and borrowed struct Market { uint256 totalSupply; uint256 supplyIndex; // Scaled by: secondsPerYear * rateDecimals uint256 supplyIndexUpdateTime; uint256 totalBorrow; uint256 borrowIndex; // Scaled by: secondsPerYear * rateDecimals uint256 borrowIndexUpdateTime; uint256 promotionReserveScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionReserveLastUpdateTime; uint256 promotionDebtScaled; // Scaled by: secondsPerYear * rateDecimals uint256 promotionDebtLastUpdateTime; } /// @notice Collaterals are assets can be used only as collateral for borrowing with no interest struct Collateral { uint256 totalCollateral; uint256 totalLiquidatedCollateral; } /// @notice Users profile for each market struct MarketAccount { mapping (address => uint) allowance; uint256 balance; uint256 accumulatedInterest; uint256 lastInterestIndex; // Scaled by: secondsPerYear * rateDecimals } /// @notice Users profile for each collateral struct CollateralAccount { mapping (address => uint) allowance; uint256 balance; uint256 lastUpdateTime; } struct MarketData { uint256 balance; uint256 interest; uint256 currentIndex; } address constant public ethAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice All rates in this contract are scaled by rateDecimals uint256 constant public rateDecimals = 10 ** 4; uint256 constant public secondsPerYear = 31536000; /// @dev For round up borrow interests uint256 constant private oneUnit = 1; /// @dev Used for calculating liquidation threshold /// @dev There is 5% gap between value to loan rate and liquidation rate uint256 constant private fivePercentLiquidationGap = 500; /// @notice Contract for getting protocol settings HoldefiSettingsInterface public holdefiSettings; /// @notice Contract for getting asset prices HoldefiPricesInterface public holdefiPrices; /// @notice Contract for holding collaterals HoldefiCollaterals public holdefiCollaterals; /// @dev Markets: marketAddress => marketDetails mapping (address => Market) public marketAssets; /// @dev Collaterals: collateralAddress => collateralDetails mapping (address => Collateral) public collateralAssets; /// @dev Markets Debt after liquidation: collateralAddress => marketAddress => marketDebtBalance mapping (address => mapping (address => uint)) public marketDebt; /// @dev Users Supplies: userAddress => marketAddress => supplyDetails mapping (address => mapping (address => MarketAccount)) private supplies; /// @dev Users Borrows: userAddress => collateralAddress => marketAddress => borrowDetails mapping (address => mapping (address => mapping (address => MarketAccount))) private borrows; /// @dev Users Collaterals: userAddress => collateralAddress => collateralDetails mapping (address => mapping (address => CollateralAccount)) private collaterals; // ----------- Events ----------- /// @notice Event emitted when a market asset is supplied event Supply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a supply is withdrawn event WithdrawSupply( address sender, address indexed supplier, address indexed market, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when a collateral asset is deposited event Collateralize( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a collateral is withdrawn event WithdrawCollateral( address sender, address indexed collateralizer, address indexed collateral, uint256 amount, uint256 balance ); /// @notice Event emitted when a market asset is borrowed event Borrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index, uint16 referralCode ); /// @notice Event emitted when a borrow is repaid event RepayBorrow( address sender, address indexed borrower, address indexed market, address indexed collateral, uint256 amount, uint256 balance, uint256 interest, uint256 index ); /// @notice Event emitted when the supply index is updated for a market asset event UpdateSupplyIndex(address indexed market, uint256 newSupplyIndex, uint256 supplyRate); /// @notice Event emitted when the borrow index is updated for a market asset event UpdateBorrowIndex(address indexed market, uint256 newBorrowIndex); /// @notice Event emitted when a collateral is liquidated event CollateralLiquidated( address indexed borrower, address indexed market, address indexed collateral, uint256 marketDebt, uint256 liquidatedCollateral ); /// @notice Event emitted when a liquidated collateral is purchased in exchange for the specified market event BuyLiquidatedCollateral( address indexed market, address indexed collateral, uint256 marketAmount, uint256 collateralAmount ); /// @notice Event emitted when HoldefiPrices contract is changed event HoldefiPricesContractChanged(address newAddress, address oldAddress); /// @notice Event emitted when a liquidation reserve is withdrawn by the owner event LiquidationReserveWithdrawn(address indexed collateral, uint256 amount); /// @notice Event emitted when a liquidation reserve is deposited event LiquidationReserveDeposited(address indexed collateral, uint256 amount); /// @notice Event emitted when a promotion reserve is withdrawn by the owner event PromotionReserveWithdrawn(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is deposited event PromotionReserveDeposited(address indexed market, uint256 amount); /// @notice Event emitted when a promotion reserve is updated event PromotionReserveUpdated(address indexed market, uint256 promotionReserve); /// @notice Event emitted when a promotion debt is updated event PromotionDebtUpdated(address indexed market, uint256 promotionDebt); /// @notice Initializes the Holdefi contract /// @param holdefiSettingsAddress Holdefi settings contract address /// @param holdefiPricesAddress Holdefi prices contract address constructor( HoldefiSettingsInterface holdefiSettingsAddress, HoldefiPricesInterface holdefiPricesAddress ) public { holdefiSettings = holdefiSettingsAddress; holdefiPrices = holdefiPricesAddress; holdefiCollaterals = new HoldefiCollaterals(); } /// @dev Modifier to check if the asset is ETH or not /// @param asset Address of the given asset modifier isNotETHAddress(address asset) { require (asset != ethAddress, "Asset should not be ETH address"); _; } /// @dev Modifier to check if the market is active or not /// @param market Address of the given market modifier marketIsActive(address market) { require (holdefiSettings.marketAssets(market).isActive, "Market is not active"); _; } /// @dev Modifier to check if the collateral is active or not /// @param collateral Address of the given collateral modifier collateralIsActive(address collateral) { require (holdefiSettings.collateralAssets(collateral).isActive, "Collateral is not active"); _; } /// @dev Modifier to check if the account address is equal to the msg.sender or not /// @param account The given account address modifier accountIsValid(address account) { require (msg.sender != account, "Account is not valid"); _; } receive() external payable { revert(); } /// @notice Returns balance and interest of an account for a given market /// @dev supplyInterest = accumulatedInterest + (balance * (marketSupplyIndex - userLastSupplyInterestIndex)) /// @param account Supplier address to get supply information /// @param market Address of the given market /// @return balance Supplied amount on the specified market /// @return interest Profit earned /// @return currentSupplyIndex Supply index for the given market at current time function getAccountSupply(address account, address market) public view returns (uint256 balance, uint256 interest, uint256 currentSupplyIndex) { balance = supplies[account][market].balance; (currentSupplyIndex,,) = getCurrentSupplyIndex(market); uint256 deltaInterestIndex = currentSupplyIndex.sub(supplies[account][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); interest = supplies[account][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns balance and interest of an account for a given market on a given collateral /// @dev borrowInterest = accumulatedInterest + (balance * (marketBorrowIndex - userLastBorrowInterestIndex)) /// @param account Borrower address to get Borrow information /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return balance Borrowed amount on the specified market /// @return interest The amount of interest the borrower should pay /// @return currentBorrowIndex Borrow index for the given market at current time function getAccountBorrow(address account, address market, address collateral) public view returns (uint256 balance, uint256 interest, uint256 currentBorrowIndex) { balance = borrows[account][collateral][market].balance; (currentBorrowIndex,,) = getCurrentBorrowIndex(market); uint256 deltaInterestIndex = currentBorrowIndex.sub(borrows[account][collateral][market].lastInterestIndex); uint256 deltaInterestScaled = deltaInterestIndex.mul(balance); uint256 deltaInterest = deltaInterestScaled.div(secondsPerYear).div(rateDecimals); if (balance > 0) { deltaInterest = deltaInterest.add(oneUnit); } interest = borrows[account][collateral][market].accumulatedInterest.add(deltaInterest); } /// @notice Returns collateral balance, time since last activity, borrow power, total borrow value, and liquidation status for a given collateral /// @dev borrowPower = (collateralValue / collateralValueToLoanRate) - totalBorrowValue /// @dev liquidationThreshold = collateralValueToLoanRate - 5% /// @dev User will be in liquidation state if (collateralValue / totalBorrowValue) < liquidationThreshold /// @param account Account address to get collateral information /// @param collateral Address of the given collateral /// @return balance Amount of the specified collateral /// @return timeSinceLastActivity Time since last activity performed by the account /// @return borrowPowerValue The borrowing power for the account of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral /// @return underCollateral A boolean value indicates whether the user is in the liquidation state or not function getAccountCollateral(address account, address collateral) public view returns ( uint256 balance, uint256 timeSinceLastActivity, uint256 borrowPowerValue, uint256 totalBorrowValue, bool underCollateral ) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; if (valueToLoanRate == 0) { return (0, 0, 0, 0, false); } balance = collaterals[account][collateral].balance; uint256 collateralValue = holdefiPrices.getAssetValueFromAmount(collateral, balance); uint256 liquidationThresholdRate = valueToLoanRate.sub(fivePercentLiquidationGap); uint256 totalBorrowPowerValue = collateralValue.mul(rateDecimals).div(valueToLoanRate); uint256 liquidationThresholdValue = collateralValue.mul(rateDecimals).div(liquidationThresholdRate); totalBorrowValue = getAccountTotalBorrowValue(account, collateral); if (totalBorrowValue > 0) { timeSinceLastActivity = block.timestamp.sub(collaterals[account][collateral].lastUpdateTime); } borrowPowerValue = 0; if (totalBorrowValue < totalBorrowPowerValue) { borrowPowerValue = totalBorrowPowerValue.sub(totalBorrowValue); } underCollateral = false; if (totalBorrowValue > liquidationThresholdValue) { underCollateral = true; } } /// @notice Returns maximum amount spender can withdraw from account supplies on a given market /// @param account Supplier address /// @param spender Spender address /// @param market Address of the given market /// @return res Maximum amount spender can withdraw from account supplies on a given market function getAccountWithdrawSupplyAllowance (address account, address spender, address market) external view returns (uint256 res) { res = supplies[account][market].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account balance on a given collateral /// @param account Account address /// @param spender Spender address /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account balance on a given collateral function getAccountWithdrawCollateralAllowance ( address account, address spender, address collateral ) external view returns (uint256 res) { res = collaterals[account][collateral].allowance[spender]; } /// @notice Returns maximum amount spender can withdraw from account borrows on a given market based on a given collteral /// @param account Borrower address /// @param spender Spender address /// @param market Address of the given market /// @param collateral Address of the given collateral /// @return res Maximum amount spender can withdraw from account borrows on a given market based on a given collteral function getAccountBorrowAllowance ( address account, address spender, address market, address collateral ) external view returns (uint256 res) { res = borrows[account][collateral][market].allowance[spender]; } /// @notice Returns total borrow value of an account based on a given collateral /// @param account Account address /// @param collateral Address of the given collateral /// @return totalBorrowValue Accumulative borrowed values on the given collateral function getAccountTotalBorrowValue (address account, address collateral) public view returns (uint256 totalBorrowValue) { MarketData memory borrowData; address market; uint256 totalDebt; uint256 assetValue; totalBorrowValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; (borrowData.balance, borrowData.interest,) = getAccountBorrow(account, market, collateral); totalDebt = borrowData.balance.add(borrowData.interest); assetValue = holdefiPrices.getAssetValueFromAmount(market, totalDebt); totalBorrowValue = totalBorrowValue.add(assetValue); } } /// @notice The collateral reserve amount for buying liquidated collateral /// @param collateral Address of the given collateral /// @return reserve Liquidation reserves for the given collateral function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } } /// @notice Returns the amount of discounted collateral can be bought in exchange for the amount of a given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param marketAmount The amount of market should be paid /// @return collateralAmountWithDiscount Amount of discounted collateral can be bought function getDiscountedCollateralAmount (address market, address collateral, uint256 marketAmount) public view returns (uint256 collateralAmountWithDiscount) { uint256 marketValue = holdefiPrices.getAssetValueFromAmount(market, marketAmount); uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 collateralValue = marketValue.mul(bonusRate).div(rateDecimals); collateralAmountWithDiscount = holdefiPrices.getAssetAmountFromValue(collateral, collateralValue); } /// @notice Returns supply index and supply rate for a given market at current time /// @dev newSupplyIndex = oldSupplyIndex + (deltaTime * supplyRate) /// @param market Address of the given market /// @return supplyIndex Supply index of the given market /// @return supplyRate Supply rate of the given market /// @return currentTime Current block timestamp function getCurrentSupplyIndex (address market) public view returns ( uint256 supplyIndex, uint256 supplyRate, uint256 currentTime ) { (, uint256 supplyRateBase, uint256 promotionRate) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 deltaTimeSupply = currentTime.sub(marketAssets[market].supplyIndexUpdateTime); supplyRate = supplyRateBase.add(promotionRate); uint256 deltaTimeInterest = deltaTimeSupply.mul(supplyRate); supplyIndex = marketAssets[market].supplyIndex.add(deltaTimeInterest); } /// @notice Returns borrow index and borrow rate for the given market at current time /// @dev newBorrowIndex = oldBorrowIndex + (deltaTime * borrowRate) /// @param market Address of the given market /// @return borrowIndex Borrow index of the given market /// @return borrowRate Borrow rate of the given market /// @return currentTime Current block timestamp function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); } /// @notice Returns promotion reserve for a given market at current time /// @dev promotionReserveScaled is scaled by (secondsPerYear * rateDecimals) /// @param market Address of the given market /// @return promotionReserveScaled Promotion reserve of the given market /// @return currentTime Current block timestamp function getPromotionReserve (address market) public view returns (uint256 promotionReserveScaled, uint256 currentTime) { (uint256 borrowRate, uint256 supplyRateBase,) = holdefiSettings.getInterests(market); currentTime = block.timestamp; uint256 allSupplyInterest = marketAssets[market].totalSupply.mul(supplyRateBase); uint256 allBorrowInterest = marketAssets[market].totalBorrow.mul(borrowRate); uint256 deltaTime = currentTime.sub(marketAssets[market].promotionReserveLastUpdateTime); uint256 currentInterest = allBorrowInterest.sub(allSupplyInterest); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(deltaTimeInterest); } /// @notice Returns promotion debt for a given market at current time /// @dev promotionDebtScaled is scaled by secondsPerYear * rateDecimals /// @param market Address of the given market /// @return promotionDebtScaled Promotion debt of the given market /// @return currentTime Current block timestamp function getPromotionDebt (address market) public view returns (uint256 promotionDebtScaled, uint256 currentTime) { uint256 promotionRate = holdefiSettings.marketAssets(market).promotionRate; currentTime = block.timestamp; promotionDebtScaled = marketAssets[market].promotionDebtScaled; if (promotionRate != 0) { uint256 deltaTime = block.timestamp.sub(marketAssets[market].promotionDebtLastUpdateTime); uint256 currentInterest = marketAssets[market].totalSupply.mul(promotionRate); uint256 deltaTimeInterest = currentInterest.mul(deltaTime); promotionDebtScaled = promotionDebtScaled.add(deltaTimeInterest); } } /// @notice Update a market supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeSupplyRate (address market) public { updateSupplyIndex(market); updatePromotionReserve(market); updatePromotionDebt(market); } /// @notice Update a market borrow index, supply index, promotion reserve, and promotion debt /// @param market Address of the given market function beforeChangeBorrowRate (address market) external { updateBorrowIndex(market); beforeChangeSupplyRate(market); } /// @notice Deposit ERC20 asset for supplying /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(msg.sender, market, amount, referralCode); } /// @notice Deposit ETH for supplying /// @notice msg.value The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supply(uint16 referralCode) external payable { supplyInternal(msg.sender, ethAddress, msg.value, referralCode); } /// @notice Sender deposits ERC20 asset belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount of asset supplier supplies /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, address market, uint256 amount, uint16 referralCode) external isNotETHAddress(market) { supplyInternal(account, market, amount, referralCode); } /// @notice Sender deposits ETH belonging to the supplier /// @notice msg.value The amount of ETH sender deposits belonging to the supplier /// @param account Address of the supplier /// @param referralCode A unique code used as an identifier of referrer function supplyBehalf(address account, uint16 referralCode) external payable { supplyInternal(account, ethAddress, msg.value, referralCode); } /// @notice Sender approves of the withdarawl for the account in the market asset /// @param account Address of the account allowed to withdrawn /// @param market Address of the given market /// @param amount The amount is allowed to withdrawn function approveWithdrawSupply(address account, address market, uint256 amount) external accountIsValid(account) marketIsActive(market) { supplies[msg.sender][market].allowance[account] = amount; } /// @notice Withdraw supply of a given market /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupply(address market, uint256 amount) external { withdrawSupplyInternal(msg.sender, market, amount); } /// @notice Sender withdraws supply belonging to the supplier /// @param account Address of the supplier /// @param market Address of the given market /// @param amount The amount will be withdrawn from the market function withdrawSupplyBehalf(address account, address market, uint256 amount) external { uint256 allowance = supplies[account][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); supplies[account][market].allowance[msg.sender] = allowance.sub(amount); withdrawSupplyInternal(account, market, amount); } /// @notice Deposit ERC20 asset as a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralize (address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(msg.sender, collateral, amount); } /// @notice Deposit ETH as a collateral /// @notice msg.value The amount of ETH will be collateralized function collateralize () external payable { collateralizeInternal(msg.sender, ethAddress, msg.value); } /// @notice Sender deposits ERC20 asset as a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be collateralized function collateralizeBehalf (address account, address collateral, uint256 amount) external isNotETHAddress(collateral) { collateralizeInternal(account, collateral, amount); } /// @notice Sender deposits ETH as a collateral belonging to the user /// @notice msg.value The amount of ETH Sender deposits as a collateral belonging to the user /// @param account Address of the user function collateralizeBehalf (address account) external payable { collateralizeInternal(account, ethAddress, msg.value); } /// @notice Sender approves the account to withdraw the collateral /// @param account Address is allowed to withdraw the collateral /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveWithdrawCollateral (address account, address collateral, uint256 amount) external accountIsValid(account) collateralIsActive(collateral) { collaterals[msg.sender][collateral].allowance[account] = amount; } /// @notice Withdraw a collateral /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateral (address collateral, uint256 amount) external { withdrawCollateralInternal(msg.sender, collateral, amount); } /// @notice Sender withdraws a collateral belonging to the user /// @param account Address of the user /// @param collateral Address of the given collateral /// @param amount The amount will be withdrawn from the collateral function withdrawCollateralBehalf (address account, address collateral, uint256 amount) external { uint256 allowance = collaterals[account][collateral].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); collaterals[account][collateral].allowance[msg.sender] = allowance.sub(amount); withdrawCollateralInternal(account, collateral, amount); } /// @notice Sender approves the account to borrow a given market based on given collateral /// @param account Address that is allowed to borrow the given market /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount is allowed to withdrawn function approveBorrow (address account, address market, address collateral, uint256 amount) external accountIsValid(account) marketIsActive(market) { borrows[msg.sender][collateral][market].allowance[account] = amount; } /// @notice Borrow an asset /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the given market will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrow (address market, address collateral, uint256 amount, uint16 referralCode) external { borrowInternal(msg.sender, market, collateral, amount, referralCode); } /// @notice Sender borrows an asset belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount will be borrowed /// @param referralCode A unique code used as an identifier of referrer function borrowBehalf (address account, address market, address collateral, uint256 amount, uint16 referralCode) external { uint256 allowance = borrows[account][collateral][market].allowance[msg.sender]; require( amount <= allowance, "Withdraw not allowed" ); borrows[account][collateral][market].allowance[msg.sender] = allowance.sub(amount); borrowInternal(account, market, collateral, amount, referralCode); } /// @notice Repay an ERC20 asset based on a given collateral /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be Repaid function repayBorrow (address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(msg.sender, market, collateral, amount); } /// @notice Repay an ETH based on a given collateral /// @notice msg.value The amount of ETH will be repaid /// @param collateral Address of the given collateral function repayBorrow (address collateral) external payable { repayBorrowInternal(msg.sender, ethAddress, collateral, msg.value); } /// @notice Sender repays an ERC20 asset based on a given collateral belonging to the borrower /// @param account Address of the borrower /// @param market Address of the given market /// @param collateral Address of the given collateral /// @param amount The amount of the market will be repaid function repayBorrowBehalf (address account, address market, address collateral, uint256 amount) external isNotETHAddress(market) { repayBorrowInternal(account, market, collateral, amount); } /// @notice Sender repays an ETH based on a given collateral belonging to the borrower /// @notice msg.value The amount of ETH sender repays belonging to the borrower /// @param account Address of the borrower /// @param collateral Address of the given collateral function repayBorrowBehalf (address account, address collateral) external payable { repayBorrowInternal(account, ethAddress, collateral, msg.value); } /// @notice Liquidate borrower's collateral /// @param borrower Address of the borrower who should be liquidated /// @param market Address of the given market /// @param collateral Address of the given collateral function liquidateBorrowerCollateral (address borrower, address market, address collateral) external whenNotPaused("liquidateBorrowerCollateral") { MarketData memory borrowData; (borrowData.balance, borrowData.interest,) = getAccountBorrow(borrower, market, collateral); require(borrowData.balance > 0, "User should have debt"); (uint256 collateralBalance, uint256 timeSinceLastActivity,,, bool underCollateral) = getAccountCollateral(borrower, collateral); require (underCollateral || (timeSinceLastActivity > secondsPerYear), "User should be under collateral or time is over" ); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); uint256 totalBorrowedBalanceValue = holdefiPrices.getAssetValueFromAmount(market, totalBorrowedBalance); uint256 liquidatedCollateralValue = totalBorrowedBalanceValue .mul(holdefiSettings.collateralAssets(collateral).penaltyRate) .div(rateDecimals); uint256 liquidatedCollateral = holdefiPrices.getAssetAmountFromValue(collateral, liquidatedCollateralValue); if (liquidatedCollateral > collateralBalance) { liquidatedCollateral = collateralBalance; } collaterals[borrower][collateral].balance = collateralBalance.sub(liquidatedCollateral); collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(liquidatedCollateral); collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.add(liquidatedCollateral); delete borrows[borrower][collateral][market]; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(borrowData.balance); marketDebt[collateral][market] = marketDebt[collateral][market].add(totalBorrowedBalance); emit CollateralLiquidated(borrower, market, collateral, totalBorrowedBalance, liquidatedCollateral); } /// @notice Buy collateral in exchange for ERC20 asset /// @param market Address of the market asset should be paid to buy collateral /// @param collateral Address of the liquidated collateral /// @param marketAmount The amount of the given market will be paid function buyLiquidatedCollateral (address market, address collateral, uint256 marketAmount) external isNotETHAddress(market) { buyLiquidatedCollateralInternal(market, collateral, marketAmount); } /// @notice Buy collateral in exchange for ETH /// @notice msg.value The amount of the given market that will be paid /// @param collateral Address of the liquidated collateral function buyLiquidatedCollateral (address collateral) external payable { buyLiquidatedCollateralInternal(ethAddress, collateral, msg.value); } /// @notice Deposit ERC20 asset as liquidation reserve /// @param collateral Address of the given collateral /// @param amount The amount that will be deposited function depositLiquidationReserve(address collateral, uint256 amount) external isNotETHAddress(collateral) { depositLiquidationReserveInternal(collateral, amount); } /// @notice Deposit ETH asset as liquidation reserve /// @notice msg.value The amount of ETH that will be deposited function depositLiquidationReserve() external payable { depositLiquidationReserveInternal(ethAddress, msg.value); } /// @notice Withdraw liquidation reserve only by the owner /// @param collateral Address of the given collateral /// @param amount The amount that will be withdrawn function withdrawLiquidationReserve (address collateral, uint256 amount) external onlyOwner { uint256 maxWithdraw = getLiquidationReserve(collateral); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } collateralAssets[collateral].totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit LiquidationReserveWithdrawn(collateral, amount); } /// @notice Deposit ERC20 asset as promotion reserve /// @param market Address of the given market /// @param amount The amount that will be deposited function depositPromotionReserve (address market, uint256 amount) external isNotETHAddress(market) { depositPromotionReserveInternal(market, amount); } /// @notice Deposit ETH as promotion reserve /// @notice msg.value The amount of ETH that will be deposited function depositPromotionReserve () external payable { depositPromotionReserveInternal(ethAddress, msg.value); } /// @notice Withdraw promotion reserve only by the owner /// @param market Address of the given market /// @param amount The amount that will be withdrawn function withdrawPromotionReserve (address market, uint256 amount) external onlyOwner { (uint256 reserveScaled,) = getPromotionReserve(market); (uint256 debtScaled,) = getPromotionDebt(market); uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); uint256 increasedDebtScaled = amountScaled.add(debtScaled); require (reserveScaled > increasedDebtScaled, "Amount should be less than max"); marketAssets[market].promotionReserveScaled = reserveScaled.sub(amountScaled); transferFromHoldefi(msg.sender, market, amount); emit PromotionReserveWithdrawn(market, amount); } /// @notice Set Holdefi prices contract only by the owner /// @param newHoldefiPrices Address of the new Holdefi prices contract function setHoldefiPricesContract (HoldefiPricesInterface newHoldefiPrices) external onlyOwner { emit HoldefiPricesContractChanged(address(newHoldefiPrices), address(holdefiPrices)); holdefiPrices = newHoldefiPrices; } /// @notice Promotion reserve and debt settlement /// @param market Address of the given market function reserveSettlement (address market) external { require(msg.sender == address(holdefiSettings), "Sender should be Holdefi Settings contract"); uint256 promotionReserve = marketAssets[market].promotionReserveScaled; uint256 promotionDebt = marketAssets[market].promotionDebtScaled; require(promotionReserve > promotionDebt, "Not enough promotion reserve"); promotionReserve = promotionReserve.sub(promotionDebt); marketAssets[market].promotionReserveScaled = promotionReserve; marketAssets[market].promotionDebtScaled = 0; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, promotionReserve); emit PromotionDebtUpdated(market, 0); } /// @notice Update supply index of a market /// @param market Address of the given market function updateSupplyIndex (address market) internal { (uint256 currentSupplyIndex, uint256 supplyRate, uint256 currentTime) = getCurrentSupplyIndex(market); marketAssets[market].supplyIndex = currentSupplyIndex; marketAssets[market].supplyIndexUpdateTime = currentTime; emit UpdateSupplyIndex(market, currentSupplyIndex, supplyRate); } /// @notice Update borrow index of a market /// @param market Address of the given market function updateBorrowIndex (address market) internal { (uint256 currentBorrowIndex,, uint256 currentTime) = getCurrentBorrowIndex(market); marketAssets[market].borrowIndex = currentBorrowIndex; marketAssets[market].borrowIndexUpdateTime = currentTime; emit UpdateBorrowIndex(market, currentBorrowIndex); } /// @notice Update promotion reserve of a market /// @param market Address of the given market function updatePromotionReserve(address market) internal { (uint256 reserveScaled,) = getPromotionReserve(market); marketAssets[market].promotionReserveScaled = reserveScaled; marketAssets[market].promotionReserveLastUpdateTime = block.timestamp; emit PromotionReserveUpdated(market, reserveScaled); } /// @notice Update promotion debt of a market /// @dev Promotion rate will be set to 0 if (promotionDebt >= promotionReserve) /// @param market Address of the given market function updatePromotionDebt(address market) internal { (uint256 debtScaled,) = getPromotionDebt(market); if (marketAssets[market].promotionDebtScaled != debtScaled){ marketAssets[market].promotionDebtScaled = debtScaled; marketAssets[market].promotionDebtLastUpdateTime = block.timestamp; emit PromotionDebtUpdated(market, debtScaled); } if (marketAssets[market].promotionReserveScaled <= debtScaled) { holdefiSettings.resetPromotionRate(market); } } /// @notice transfer ETH or ERC20 asset from this contract function transferFromHoldefi(address receiver, address asset, uint256 amount) internal { bool success = false; if (asset == ethAddress){ (success, ) = receiver.call{value:amount}(""); } else { IERC20 token = IERC20(asset); success = token.transfer(receiver, amount); } require (success, "Cannot Transfer"); } /// @notice transfer ERC20 asset to this contract function transferToHoldefi(address receiver, address asset, uint256 amount) internal { IERC20 token = IERC20(asset); bool success = token.transferFrom(msg.sender, receiver, amount); require (success, "Cannot Transfer"); } /// @notice Perform supply operation function supplyInternal(address account, address market, uint256 amount, uint16 referralCode) internal whenNotPaused("supply") marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); supplyData.balance = supplyData.balance.add(amount); supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.add(amount); emit Supply( msg.sender, account, market, amount, supplyData.balance, supplyData.interest, supplyData.currentIndex, referralCode ); } /// @notice Perform withdraw supply operation function withdrawSupplyInternal (address account, address market, uint256 amount) internal whenNotPaused("withdrawSupply") { MarketData memory supplyData; (supplyData.balance, supplyData.interest, supplyData.currentIndex) = getAccountSupply(account, market); uint256 totalSuppliedBalance = supplyData.balance.add(supplyData.interest); require (totalSuppliedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalSuppliedBalance){ transferAmount = totalSuppliedBalance; } uint256 remaining = 0; if (transferAmount <= supplyData.interest) { supplyData.interest = supplyData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(supplyData.interest); supplyData.interest = 0; supplyData.balance = supplyData.balance.sub(remaining); } supplies[account][market].balance = supplyData.balance; supplies[account][market].accumulatedInterest = supplyData.interest; supplies[account][market].lastInterestIndex = supplyData.currentIndex; beforeChangeSupplyRate(market); marketAssets[market].totalSupply = marketAssets[market].totalSupply.sub(remaining); transferFromHoldefi(msg.sender, market, transferAmount); emit WithdrawSupply( msg.sender, account, market, transferAmount, supplyData.balance, supplyData.interest, supplyData.currentIndex ); } /// @notice Perform collateralize operation function collateralizeInternal (address account, address collateral, uint256 amount) internal whenNotPaused("collateralize") collateralIsActive(collateral) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } uint256 balance = collaterals[account][collateral].balance.add(amount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.add(amount); emit Collateralize(msg.sender, account, collateral, amount, balance); } /// @notice Perform withdraw collateral operation function withdrawCollateralInternal (address account, address collateral, uint256 amount) internal whenNotPaused("withdrawCollateral") { (uint256 balance,, uint256 borrowPowerValue, uint256 totalBorrowValue,) = getAccountCollateral(account, collateral); require (borrowPowerValue != 0, "Borrow power should not be zero"); uint256 collateralNedeed = 0; if (totalBorrowValue != 0) { uint256 valueToLoanRate = holdefiSettings.collateralAssets(collateral).valueToLoanRate; uint256 totalCollateralValue = totalBorrowValue.mul(valueToLoanRate).div(rateDecimals); collateralNedeed = holdefiPrices.getAssetAmountFromValue(collateral, totalCollateralValue); } uint256 maxWithdraw = balance.sub(collateralNedeed); uint256 transferAmount = amount; if (transferAmount > maxWithdraw){ transferAmount = maxWithdraw; } balance = balance.sub(transferAmount); collaterals[account][collateral].balance = balance; collaterals[account][collateral].lastUpdateTime = block.timestamp; collateralAssets[collateral].totalCollateral = collateralAssets[collateral].totalCollateral.sub(transferAmount); holdefiCollaterals.withdraw(collateral, msg.sender, transferAmount); emit WithdrawCollateral(msg.sender, account, collateral, transferAmount, balance); } /// @notice Perform borrow operation function borrowInternal (address account, address market, address collateral, uint256 amount, uint16 referralCode) internal whenNotPaused("borrow") marketIsActive(market) collateralIsActive(collateral) { require ( amount <= (marketAssets[market].totalSupply.sub(marketAssets[market].totalBorrow)), "Amount should be less than cash" ); (,, uint256 borrowPowerValue,,) = getAccountCollateral(account, collateral); uint256 assetToBorrowValue = holdefiPrices.getAssetValueFromAmount(market, amount); require ( borrowPowerValue >= assetToBorrowValue, "Borrow power should be more than new borrow value" ); MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); borrowData.balance = borrowData.balance.add(amount); borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.add(amount); transferFromHoldefi(msg.sender, market, amount); emit Borrow( msg.sender, account, market, collateral, amount, borrowData.balance, borrowData.interest, borrowData.currentIndex, referralCode ); } /// @notice Perform repay borrow operation function repayBorrowInternal (address account, address market, address collateral, uint256 amount) internal whenNotPaused("repayBorrow") { MarketData memory borrowData; (borrowData.balance, borrowData.interest, borrowData.currentIndex) = getAccountBorrow(account, market, collateral); uint256 totalBorrowedBalance = borrowData.balance.add(borrowData.interest); require (totalBorrowedBalance != 0, "Total balance should not be zero"); uint256 transferAmount = amount; if (transferAmount > totalBorrowedBalance) { transferAmount = totalBorrowedBalance; if (market == ethAddress) { uint256 extra = amount.sub(transferAmount); transferFromHoldefi(msg.sender, ethAddress, extra); } } if (market != ethAddress) { transferToHoldefi(address(this), market, transferAmount); } uint256 remaining = 0; if (transferAmount <= borrowData.interest) { borrowData.interest = borrowData.interest.sub(transferAmount); } else { remaining = transferAmount.sub(borrowData.interest); borrowData.interest = 0; borrowData.balance = borrowData.balance.sub(remaining); } borrows[account][collateral][market].balance = borrowData.balance; borrows[account][collateral][market].accumulatedInterest = borrowData.interest; borrows[account][collateral][market].lastInterestIndex = borrowData.currentIndex; collaterals[account][collateral].lastUpdateTime = block.timestamp; beforeChangeSupplyRate(market); marketAssets[market].totalBorrow = marketAssets[market].totalBorrow.sub(remaining); emit RepayBorrow ( msg.sender, account, market, collateral, transferAmount, borrowData.balance, borrowData.interest, borrowData.currentIndex ); } /// @notice Perform buy liquidated collateral operation function buyLiquidatedCollateralInternal (address market, address collateral, uint256 marketAmount) internal whenNotPaused("buyLiquidatedCollateral") { uint256 debt = marketDebt[collateral][market]; require (marketAmount <= debt, "Amount should be less than total liquidated assets" ); uint256 collateralAmountWithDiscount = getDiscountedCollateralAmount(market, collateral, marketAmount); uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; require ( collateralAmountWithDiscount <= totalLiquidatedCollateral, "Collateral amount with discount should be less than total liquidated assets" ); if (market != ethAddress) { transferToHoldefi(address(this), market, marketAmount); } collateralAssets[collateral].totalLiquidatedCollateral = totalLiquidatedCollateral.sub(collateralAmountWithDiscount); marketDebt[collateral][market] = debt.sub(marketAmount); holdefiCollaterals.withdraw(collateral, msg.sender, collateralAmountWithDiscount); emit BuyLiquidatedCollateral(market, collateral, marketAmount, collateralAmountWithDiscount); } /// @notice Perform deposit promotion reserve operation function depositPromotionReserveInternal (address market, uint256 amount) internal marketIsActive(market) { if (market != ethAddress) { transferToHoldefi(address(this), market, amount); } uint256 amountScaled = amount.mul(secondsPerYear).mul(rateDecimals); marketAssets[market].promotionReserveScaled = marketAssets[market].promotionReserveScaled.add(amountScaled); emit PromotionReserveDeposited(market, amount); } /// @notice Perform deposit liquidation reserve operation function depositLiquidationReserveInternal (address collateral, uint256 amount) internal collateralIsActive(ethAddress) { if (collateral != ethAddress) { transferToHoldefi(address(holdefiCollaterals), collateral, amount); } else { transferFromHoldefi(address(holdefiCollaterals), collateral, amount); } collateralAssets[ethAddress].totalLiquidatedCollateral = collateralAssets[ethAddress].totalLiquidatedCollateral.add(msg.value); emit LiquidationReserveDeposited(ethAddress, msg.value); } }
Returns borrow index and borrow rate for the given market at current time newBorrowIndex = oldBorrowIndex + (deltaTime borrowRate) market Address of the given market return borrowIndex Borrow index of the given market return borrowRate Borrow rate of the given market return currentTime Current block timestamp
function getCurrentBorrowIndex (address market) public view returns ( uint256 borrowIndex, uint256 borrowRate, uint256 currentTime ) { borrowRate = holdefiSettings.marketAssets(market).borrowRate; currentTime = block.timestamp; uint256 deltaTimeBorrow = currentTime.sub(marketAssets[market].borrowIndexUpdateTime); uint256 deltaTimeInterest = deltaTimeBorrow.mul(borrowRate); borrowIndex = marketAssets[market].borrowIndex.add(deltaTimeInterest); }
13,514,333
pragma solidity ^0.4.11; // ---------------------------------------------------------------------------- // OAX 'openANX Token' crowdfunding contract - locked tokens // // Refer to http://openanx.org/ for further information. // // Enjoy. (c) openANX and BokkyPooBah / Bok Consulting Pty Ltd 2017. // The MIT Licence. // ---------------------------------------------------------------------------- import "./ERC20Interface.sol"; import "./SafeMath.sol"; import "./OpenANXTokenConfig.sol"; // ---------------------------------------------------------------------------- // Contract that holds the 1Y and 2Y locked token information // ---------------------------------------------------------------------------- contract LockedTokens is OpenANXTokenConfig { using SafeMath for uint; // ------------------------------------------------------------------------ // 1y and 2y locked totals, not including unsold tranche1 and all tranch2 // tokens // ------------------------------------------------------------------------ uint public constant TOKENS_LOCKED_1Y_TOTAL = 14000000 * DECIMALSFACTOR; uint public constant TOKENS_LOCKED_2Y_TOTAL = 26000000 * DECIMALSFACTOR; // ------------------------------------------------------------------------ // Current totalSupply of 1y and 2y locked tokens // ------------------------------------------------------------------------ uint public totalSupplyLocked1Y; uint public totalSupplyLocked2Y; // ------------------------------------------------------------------------ // Locked tokens mapping // ------------------------------------------------------------------------ mapping (address => uint) public balancesLocked1Y; mapping (address => uint) public balancesLocked2Y; // ------------------------------------------------------------------------ // Address of openANX crowdsale token contract // ------------------------------------------------------------------------ ERC20Interface public tokenContract; // ------------------------------------------------------------------------ // Constructor - called by crowdsale token contract // ------------------------------------------------------------------------ function LockedTokens(address _tokenContract) { tokenContract = ERC20Interface(_tokenContract); // --- 1y locked tokens --- // Advisors add1Y(0xaBBa43E7594E3B76afB157989e93c6621497FD4b, 2000000 * DECIMALSFACTOR); // Directors add1Y(0xacCa534c9f62Ab495bd986e002DdF0f054caAE4f, 2000000 * DECIMALSFACTOR); // Early backers add1Y(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR); // Developers add1Y(0xaeEa63B5479B50F79583ec49DACdcf86DDEff392, 8000000 * DECIMALSFACTOR); // Confirm 1Y totals assert(totalSupplyLocked1Y == TOKENS_LOCKED_1Y_TOTAL); // --- 2y locked tokens --- // Foundation add2Y(0xAAAA9De1E6C564446EBCA0fd102D8Bd92093c756, 20000000 * DECIMALSFACTOR); // Advisors add2Y(0xaBBa43E7594E3B76afB157989e93c6621497FD4b, 2000000 * DECIMALSFACTOR); // Directors add2Y(0xacCa534c9f62Ab495bd986e002DdF0f054caAE4f, 2000000 * DECIMALSFACTOR); // Early backers add2Y(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR); // Confirm 2Y totals assert(totalSupplyLocked2Y == TOKENS_LOCKED_2Y_TOTAL); } // ------------------------------------------------------------------------ // Add remaining tokens to locked 1y balances // ------------------------------------------------------------------------ function addRemainingTokens() { // Only the crowdsale contract can call this function if (msg.sender != address(tokenContract)) throw; // Total tokens to be created uint remainingTokens = TOKENS_TOTAL; // Minus precommitments and public crowdsale tokens remainingTokens = remainingTokens.sub(tokenContract.totalSupply()); // Minus 1y locked tokens remainingTokens = remainingTokens.sub(totalSupplyLocked1Y); // Minus 2y locked tokens remainingTokens = remainingTokens.sub(totalSupplyLocked2Y); // Unsold tranche1 and tranche2 tokens to be locked for 1y add1Y(address(tokenContract), remainingTokens); } // ------------------------------------------------------------------------ // Add to 1y locked balances and totalSupply // ------------------------------------------------------------------------ function add1Y(address account, uint value) private { balancesLocked1Y[account] = balancesLocked1Y[account].add(value); totalSupplyLocked1Y = totalSupplyLocked1Y.add(value); } // ------------------------------------------------------------------------ // Add to 2y locked balances and totalSupply // ------------------------------------------------------------------------ function add2Y(address account, uint value) private { balancesLocked2Y[account] = balancesLocked2Y[account].add(value); totalSupplyLocked2Y = totalSupplyLocked2Y.add(value); } // ------------------------------------------------------------------------ // 1y locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked1Y(address account) constant returns (uint balance) { return balancesLocked1Y[account]; } // ------------------------------------------------------------------------ // 2y locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked2Y(address account) constant returns (uint balance) { return balancesLocked2Y[account]; } // ------------------------------------------------------------------------ // 1y and 2y locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked(address account) constant returns (uint balance) { return balancesLocked1Y[account].add(balancesLocked2Y[account]); } // ------------------------------------------------------------------------ // 1y and 2y locked total supply // ------------------------------------------------------------------------ function totalSupplyLocked() constant returns (uint) { return totalSupplyLocked1Y + totalSupplyLocked2Y; } // ------------------------------------------------------------------------ // An account can unlock their 1y locked tokens 1y after token launch date // ------------------------------------------------------------------------ function unlock1Y() { if (now < LOCKED_1Y_DATE) throw; uint amount = balancesLocked1Y[msg.sender]; if (amount == 0) throw; balancesLocked1Y[msg.sender] = 0; totalSupplyLocked1Y = totalSupplyLocked1Y.sub(amount); if (!tokenContract.transfer(msg.sender, amount)) throw; } // ------------------------------------------------------------------------ // An account can unlock their 2y locked tokens 2y after token launch date // ------------------------------------------------------------------------ function unlock2Y() { if (now < LOCKED_2Y_DATE) throw; uint amount = balancesLocked2Y[msg.sender]; if (amount == 0) throw; balancesLocked2Y[msg.sender] = 0; totalSupplyLocked2Y = totalSupplyLocked2Y.sub(amount); if (!tokenContract.transfer(msg.sender, amount)) throw; } }
------------------------------------------------------------------------ Add to 1y locked balances and totalSupply ------------------------------------------------------------------------
function add1Y(address account, uint value) private { balancesLocked1Y[account] = balancesLocked1Y[account].add(value); totalSupplyLocked1Y = totalSupplyLocked1Y.add(value); }
5,428,387
// SPDX-License-Identifier: MIT // Created by Flux Team // Copy from Compund and editor by Flux. pragma solidity 0.6.8; import "./SafeMath.sol"; struct Exp { uint256 mantissa; } library Exponential { using SafeMath for uint256; uint256 private constant expScale = 1e18; // solhint-disable-line const-name-snakecase uint256 private constant halfExpScale = expScale / 2; // solhint-disable-line const-name-snakecase /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function get(uint256 num, uint256 denom) internal pure returns (Exp memory) { return Exp({ mantissa: num.mul(expScale).div(denom) }); } /** * @dev Adds two exponentials, returning a get exponential. */ function add(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return Exp({ mantissa: a.mantissa.add(b.mantissa) }); } /** * @dev Subtracts two exponentials, returning a get exponential. */ function sub(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return (Exp({ mantissa: a.mantissa.sub(b.mantissa) })); } /** * @dev Multiply an Exp by a scalar, returning a get Exp. */ function mulScalar(Exp memory a, uint256 scalar) internal pure returns (Exp memory) { return (Exp({ mantissa: a.mantissa.mul(scalar) })); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) { return (truncate(mulScalar(a, scalar))); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt( Exp memory a, uint256 scalar, uint256 addend ) internal pure returns (uint256) { return mulScalarTruncate(a, scalar).add(addend); } /** * @dev Divide an Exp by a scalar, returning a get Exp. */ function divScalar(Exp memory a, uint256 scalar) internal pure returns (Exp memory) { return (Exp({ mantissa: a.mantissa.div(scalar) })); } /** * @dev Divide a scalar by an Exp, returning a get Exp. */ function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) { /* We are doing this as: get(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ // s/divisor = (s*1e18)/(divisor) return get(scalar.mul(expScale), divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) { return (truncate(divScalarByExp(scalar, divisor))); } /** * @dev Multiplies two exponentials, returning a get exponential. */ function mul(Exp memory a, Exp memory b) internal pure returns (Exp memory) { uint256 doubleScaledProduct = a.mantissa.mul(b.mantissa); // 100*3 * 100*4 / 10 /100 // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. uint256 doubleScaledProductWithHalfScale = doubleScaledProduct.add(halfExpScale); return (Exp({ mantissa: doubleScaledProductWithHalfScale.div(expScale) })); } /** * @dev Multiplies two exponentials given their mantissas, returning a get exponential. */ function mul(uint256 a, uint256 b) internal pure returns (Exp memory) { return mul(Exp({ mantissa: a }), Exp({ mantissa: b })); } /** * @dev Multiplies three exponentials, returning a get exponential. */ function mul3( Exp memory a, Exp memory b, Exp memory c ) internal pure returns (Exp memory) { return mul(mul(a, b), c); } /** * @dev Divides two exponentials, returning a get exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling get(a.mantissa, b.mantissa) */ function div(Exp memory a, Exp memory b) internal pure returns (Exp memory) { return get(a.mantissa, b.mantissa); } /** @dev 两个数字相除,但允许除数 b 为 0 */ function divAllowZero(Exp memory a, Exp memory b) internal pure returns (Exp memory) { if (b.mantissa == 0) { return Exp({ mantissa: 0 }); } return get(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) internal pure returns (uint256) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThan(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqual(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThan(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa > right.mantissa; } /** * @dev Checks if left Exp = right Exp. */ function equal(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa == right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZero(Exp memory value) internal pure returns (bool) { return value.mantissa == 0; } }
Checks if left Exp <= right Exp./
function lessThanOrEqual(Exp memory left, Exp memory right) internal pure returns (bool) { return left.mantissa <= right.mantissa; }
5,451,362
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {GammaOperator} from "./GammaOperator.sol"; import {IGammaRedeemerV1} from "./interfaces/IGammaRedeemerV1.sol"; import {IPokeMe} from "./interfaces/IPokeMe.sol"; import {ITaskTreasury} from "./interfaces/ITaskTreasury.sol"; import {IResolver} from "./interfaces/IResolver.sol"; /// @author Willy Shen /// @title Gamma Automatic Redeemer /// @notice An automatic redeemer for Gmma otoken holders and writers contract GammaRedeemerV1 is IGammaRedeemerV1, GammaOperator { Order[] public orders; IPokeMe public automator; ITaskTreasury public automatorTreasury; bool public isAutomatorEnabled; // fee in 1/10.000: 1% = 100, 0.01% = 1 uint256 public redeemFee = 50; uint256 public settleFee = 10; /** * @notice only automator or owner */ modifier onlyAuthorized() { require( msg.sender == address(automator) || msg.sender == owner(), "GammaRedeemer::onlyAuthorized: Only automator or owner" ); _; } constructor( address _gammaAddressBook, address _automator, address _automatorTreasury ) GammaOperator(_gammaAddressBook) { automator = IPokeMe(_automator); automatorTreasury = ITaskTreasury(_automatorTreasury); isAutomatorEnabled = false; } function startAutomator(address _resolver) public onlyOwner { require(!isAutomatorEnabled); isAutomatorEnabled = true; automator.createTask( address(this), bytes4(keccak256("processOrders(uint256[])")), _resolver, abi.encodeWithSelector(IResolver.getProcessableOrders.selector) ); } function stopAutomator() public onlyOwner { require(isAutomatorEnabled); isAutomatorEnabled = false; automator.cancelTask( automator.getTaskId( address(this), address(this), bytes4(keccak256("processOrders(uint256[])")) ) ); } /** * @notice create automation order * @param _otoken the address of otoken (only holders) * @param _amount amount of otoken (only holders) * @param _vaultId the id of specific vault to settle (only writers) */ function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) public override { uint256 fee; bool isSeller; if (_otoken == address(0)) { require( _amount == 0, "GammaRedeemer::createOrder: Amount must be 0 when creating settlement order" ); fee = settleFee; isSeller = true; } else { require( isWhitelistedOtoken(_otoken), "GammaRedeemer::createOrder: Otoken not whitelisted" ); fee = redeemFee; } uint256 orderId = orders.length; Order memory order; order.owner = msg.sender; order.otoken = _otoken; order.amount = _amount; order.vaultId = _vaultId; order.isSeller = isSeller; order.fee = fee; orders.push(order); emit OrderCreated(orderId, msg.sender, _otoken); } /** * @notice cancel automation order * @param _orderId the id of specific order to be cancelled */ function cancelOrder(uint256 _orderId) public override { Order storage order = orders[_orderId]; require( order.owner == msg.sender, "GammaRedeemer::cancelOrder: Sender is not order owner" ); require( !order.finished, "GammaRedeemer::cancelOrder: Order is already finished" ); order.finished = true; emit OrderFinished(_orderId, true); } /** * @notice check if processing order is profitable * @param _orderId the id of specific order to be processed * @return true if settling vault / redeeming returns more than 0 amount */ function shouldProcessOrder(uint256 _orderId) public view override returns (bool) { Order memory order = orders[_orderId]; if (order.finished) return false; if (order.isSeller) { bool shouldSettle = shouldSettleVault(order.owner, order.vaultId); if (!shouldSettle) return false; } else { bool shouldRedeem = shouldRedeemOtoken( order.owner, order.otoken, order.amount ); if (!shouldRedeem) return false; } return true; } /** * @notice process an order * @dev only automator allowed * @param _orderId the id of specific order to process */ function processOrder(uint256 _orderId) public override onlyAuthorized { Order storage order = orders[_orderId]; require( !order.finished, "GammaRedeemer::processOrder: Order is already finished" ); require( shouldProcessOrder(_orderId), "GammaRedeemer::processOrder: Order should not be processed" ); order.finished = true; if (order.isSeller) { settleVault(order.owner, order.vaultId, order.fee); } else { redeemOtoken(order.owner, order.otoken, order.amount, order.fee); } emit OrderFinished(_orderId, false); } /** * @notice process multiple orders * @param _orderIds array of order ids to process */ function processOrders(uint256[] calldata _orderIds) public { for (uint256 i = 0; i < _orderIds.length; i++) { processOrder(_orderIds[i]); } } /** * @notice withdraw funds from automator * @param _token address of token to withdraw * @param _amount amount of token to withdraw */ function withdrawFund(address _token, uint256 _amount) public onlyOwner { automatorTreasury.withdrawFunds(payable(this), _token, _amount); } function setAutomator(address _automator) public onlyOwner { automator = IPokeMe(_automator); } function setAutomatorTreasury(address _automatorTreasury) public onlyOwner { automatorTreasury = ITaskTreasury(_automatorTreasury); } function setRedeemFee(uint256 _redeemFee) public onlyOwner { redeemFee = _redeemFee; } function setSettleFee(uint256 _settleFee) public onlyOwner { settleFee = _settleFee; } function getOrdersLength() public view override returns (uint256) { return orders.length; } function getOrders() public view override returns (Order[] memory) { return orders; } function getOrder(uint256 _orderId) public view override returns (Order memory) { return orders[_orderId]; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {IAddressBook} from "./interfaces/IAddressBook.sol"; import {IGammaController} from "./interfaces/IGammaController.sol"; import {IWhitelist} from "./interfaces/IWhitelist.sol"; import {IMarginCalculator} from "./interfaces/IMarginCalculator.sol"; import {Actions} from "./external/OpynActions.sol"; import {MarginVault} from "./external/OpynVault.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IOtoken} from "./interfaces/IOtoken.sol"; /// @author Willy Shen /// @title Gamma Operator /// @notice Opyn Gamma protocol adapter for redeeming otokens and settling vaults contract GammaOperator is Ownable { using SafeERC20 for IERC20; // Gamma Protocol contracts IAddressBook public addressBook; IGammaController public controller; IWhitelist public whitelist; IMarginCalculator public calculator; /** * @dev fetch Gamma contracts from address book * @param _addressBook Gamma Address Book address */ constructor(address _addressBook) { setAddressBook(_addressBook); refreshConfig(); } /** * @notice redeem otoken on behalf of user * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @param _fee fee in 1/10.000 */ function redeemOtoken( address _owner, address _otoken, uint256 _amount, uint256 _fee ) internal { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); IERC20(_otoken).safeTransferFrom(_owner, address(this), actualAmount); Actions.ActionArgs memory action; action.actionType = Actions.ActionType.Redeem; action.secondAddress = address(this); action.asset = _otoken; action.amount = _amount; Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; IERC20 collateral = IERC20(IOtoken(_otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice settle vault on behalf of user * @param _owner owner address * @param _vaultId vaultId to settle * @param _fee fee in 1/10.000 */ function settleVault( address _owner, uint256 _vaultId, uint256 _fee ) internal { Actions.ActionArgs memory action; action.actionType = Actions.ActionType.SettleVault; action.owner = _owner; action.vaultId = _vaultId; action.secondAddress = address(this); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); actions[0] = action; (MarginVault.Vault memory vault, , ) = getVaultWithDetails( _owner, _vaultId ); address otoken = getVaultOtoken(vault); IERC20 collateral = IERC20(IOtoken(otoken).collateralAsset()); uint256 startAmount = collateral.balanceOf(address(this)); controller.operate(actions); uint256 endAmount = collateral.balanceOf(address(this)); uint256 difference = endAmount - startAmount; uint256 finalAmount = difference - ((_fee * difference) / 10000); collateral.safeTransfer(_owner, finalAmount); } /** * @notice return if otoken should be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return true if otoken has expired and payout is greater than zero */ function shouldRedeemOtoken( address _owner, address _otoken, uint256 _amount ) public view returns (bool) { uint256 actualAmount = getRedeemableAmount(_owner, _otoken, _amount); try this.getRedeemPayout(_otoken, actualAmount) returns ( uint256 payout ) { if (payout == 0) return false; } catch { return false; } return true; } /** * @notice return if vault should be settled * @param _owner owner address * @param _vaultId vaultId to settle * @return true if vault can be settled, contract is operator of owner, * and excess collateral is greater than zero */ function shouldSettleVault(address _owner, uint256 _vaultId) public view returns (bool) { ( MarginVault.Vault memory vault, uint256 typeVault, ) = getVaultWithDetails(_owner, _vaultId); (uint256 payout, bool isValidVault) = getExcessCollateral( vault, typeVault ); if (!isValidVault || payout == 0) return false; return true; } /** * @notice set Gamma Address Book * @param _address Address Book address */ function setAddressBook(address _address) public onlyOwner { require( _address != address(0), "GammaOperator::setAddressBook: Address must not be zero" ); addressBook = IAddressBook(_address); } /** * @notice transfer operator profit * @param _token address token to transfer * @param _amount amount of token to transfer * @param _to transfer destination */ function harvest( address _token, uint256 _amount, address _to ) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { (bool success, ) = _to.call{value: _amount}(""); require(success, "GammaOperator::harvest: ETH transfer failed"); } else { IERC20(_token).safeTransfer(_to, _amount); } } /** * @notice refresh Gamma contracts' addresses */ function refreshConfig() public { address _controller = addressBook.getController(); controller = IGammaController(_controller); address _whitelist = addressBook.getWhitelist(); whitelist = IWhitelist(_whitelist); address _calculator = addressBook.getMarginCalculator(); calculator = IMarginCalculator(_calculator); } /** * @notice get an oToken's payout in the collateral asset * @param _otoken otoken address * @param _amount amount of otoken to redeem */ function getRedeemPayout(address _otoken, uint256 _amount) public view returns (uint256) { return controller.getPayout(_otoken, _amount); } /** * @notice get amount of otoken that can be redeemed * @param _owner owner address * @param _otoken otoken address * @param _amount amount of otoken * @return amount of otoken the contract can transferFrom owner */ function getRedeemableAmount( address _owner, address _otoken, uint256 _amount ) public view returns (uint256) { uint256 ownerBalance = IERC20(_otoken).balanceOf(_owner); uint256 allowance = IERC20(_otoken).allowance(_owner, address(this)); uint256 spendable = min(ownerBalance, allowance); return min(_amount, spendable); } /** * @notice return details of a specific vault * @param _owner owner address * @param _vaultId vaultId * @return vault struct and vault type and the latest timestamp when the vault was updated */ function getVaultWithDetails(address _owner, uint256 _vaultId) public view returns ( MarginVault.Vault memory, uint256, uint256 ) { return controller.getVaultWithDetails(_owner, _vaultId); } /** * @notice return the otoken from specific vault * @param _vault vault struct * @return otoken address */ function getVaultOtoken(MarginVault.Vault memory _vault) public pure returns (address) { bool hasShort = isNotEmpty(_vault.shortOtokens); bool hasLong = isNotEmpty(_vault.longOtokens); assert(hasShort || hasLong); return hasShort ? _vault.shortOtokens[0] : _vault.longOtokens[0]; } /** * @notice return amount of collateral that can be removed from a vault * @param _vault vault struct * @param _typeVault vault type * @return excess amount and true if excess is greater than zero */ function getExcessCollateral( MarginVault.Vault memory _vault, uint256 _typeVault ) public view returns (uint256, bool) { return calculator.getExcessCollateral(_vault, _typeVault); } /** * @notice return if otoken is ready to be settled * @param _otoken otoken address * @return true if settlement is allowed */ function isSettlementAllowed(address _otoken) public view returns (bool) { return controller.isSettlementAllowed(_otoken); } /** * @notice return if this contract is Gamma operator of an address * @param _owner owner address * @return true if address(this) is operator of _owner */ function isOperatorOf(address _owner) public view returns (bool) { return controller.isOperator(_owner, address(this)); } /** * @notice return if otoken is whitelisted on Gamma * @param _otoken otoken address * @return true if isWhitelistedOtoken returns true for _otoken */ function isWhitelistedOtoken(address _otoken) public view returns (bool) { return whitelist.isWhitelistedOtoken(_otoken); } /** * @param _otoken otoken address * @return true if otoken has expired and settlement is allowed */ function hasExpiredAndSettlementAllowed(address _otoken) public view returns (bool) { bool hasExpired = block.timestamp >= IOtoken(_otoken).expiryTimestamp(); if (!hasExpired) return false; bool isAllowed = isSettlementAllowed(_otoken); if (!isAllowed) return false; return true; } /** * @notice return if specific vault exist * @param _owner owner address * @param _vaultId vaultId to check * @return true if vault exist for owner */ function isValidVaultId(address _owner, uint256 _vaultId) public view returns (bool) { uint256 vaultCounter = controller.getAccountVaultCounter(_owner); return ((_vaultId > 0) && (_vaultId <= vaultCounter)); } /** * @notice return if array is not empty * @param _array array of address to check * @return true if array length is grreater than zero & first element isn't address zero */ function isNotEmpty(address[] memory _array) private pure returns (bool) { return (_array.length > 0) && (_array[0] != address(0)); } /** * @notice return the lowest number * @param a first number * @param b second number * @return the lowest uint256 */ function min(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? b : a; } receive() external payable {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; interface IGammaRedeemerV1 { struct Order { // address of user address owner; // address of otoken to redeem address otoken; // amount of otoken to redeem uint256 amount; // vaultId of vault to settle uint256 vaultId; // true if settle vault order, else redeem otoken bool isSeller; // convert proceed to ETH, currently unused bool toETH; // fee in 1/10.000 uint256 fee; // true if order is already processed bool finished; } event OrderCreated( uint256 indexed orderId, address indexed owner, address indexed otoken ); event OrderFinished(uint256 indexed orderId, bool indexed cancelled); function createOrder( address _otoken, uint256 _amount, uint256 _vaultId ) external; function cancelOrder(uint256 _orderId) external; function shouldProcessOrder(uint256 _orderId) external view returns (bool); function processOrder(uint256 _orderId) external; function getOrdersLength() external view returns (uint256); function getOrders() external view returns (Order[] memory); function getOrder(uint256 _orderId) external view returns (Order memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IPokeMe { function createTask( address _execAddress, bytes4 _execSelector, address _resolverAddress, bytes calldata _resolverData ) external; function cancelTask(bytes32 _taskId) external; // function withdrawFunds(uint256 _amount) external; function getTaskId( address _taskCreator, address _execAddress, bytes4 _selector ) external pure returns (bytes32); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface ITaskTreasury { function withdrawFunds( address payable _receiver, address _token, uint256 _amount ) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IResolver { function getProcessableOrders() external returns (uint256[] memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IAddressBook { function getOtokenImpl() external view returns (address); function getOtokenFactory() external view returns (address); function getWhitelist() external view returns (address); function getController() external view returns (address); function getOracle() external view returns (address); function getMarginPool() external view returns (address); function getMarginCalculator() external view returns (address); function getLiquidationManager() external view returns (address); function getAddress(bytes32 _id) external view returns (address); /* Setters */ function setOtokenImpl(address _otokenImpl) external; function setOtokenFactory(address _factory) external; function setOracleImpl(address _otokenImpl) external; function setWhitelist(address _whitelist) external; function setController(address _controller) external; function setMarginPool(address _marginPool) external; function setMarginCalculator(address _calculator) external; function setLiquidationManager(address _liquidationManager) external; function setAddress(bytes32 _id, address _newImpl) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {Actions} from "../external/OpynActions.sol"; import {MarginVault} from "../external/OpynVault.sol"; interface IGammaController { function operate(Actions.ActionArgs[] memory _actions) external; function isSettlementAllowed(address _otoken) external view returns (bool); function isOperator(address _owner, address _operator) external view returns (bool); function getPayout(address _otoken, uint256 _amount) external view returns (uint256); function getVaultWithDetails(address _owner, uint256 _vaultId) external view returns ( MarginVault.Vault memory, uint256, uint256 ); function getAccountVaultCounter(address _accountOwner) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; interface IWhitelist { function isWhitelistedOtoken(address _otoken) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.0; import {MarginVault} from "../external/OpynVault.sol"; interface IMarginCalculator { function getExcessCollateral( MarginVault.Vault calldata _vault, uint256 _vaultType ) external view returns (uint256 netValue, bool isExcess); } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title Actions * @author Opyn Team * @notice A library that provides a ActionArgs struct, sub types of Action structs, and functions to parse ActionArgs into specific Actions. */ library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct MintArgs { // address of the account owner address owner; // index of the vault from which the asset will be minted uint256 vaultId; // address to which we transfer the minted oTokens address to; // oToken that is to be minted address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be minted uint256 amount; } struct BurnArgs { // address of the account owner address owner; // index of the vault from which the oToken will be burned uint256 vaultId; // address from which we transfer the oTokens address from; // oToken that is to be burned address otoken; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of oTokens that is to be burned uint256 amount; } struct OpenVaultArgs { // address of the account owner address owner; // vault id to create uint256 vaultId; // vault type, 0 for spread/max loss and 1 for naked margin vault uint256 vaultType; } struct DepositArgs { // address of the account owner address owner; // index of the vault to which the asset will be added uint256 vaultId; // address from which we transfer the asset address from; // asset that is to be deposited address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be deposited uint256 amount; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } struct WithdrawArgs { // address of the account owner address owner; // index of the vault from which the asset will be withdrawn uint256 vaultId; // address to which we transfer the asset address to; // asset that is to be withdrawn address asset; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // amount of asset that is to be withdrawn uint256 amount; } struct SettleVaultArgs { // address of the account owner address owner; // index of the vault to which is to be settled uint256 vaultId; // address to which we transfer the remaining collateral address to; } struct LiquidateArgs { // address of the vault owner to liquidate address owner; // address of the liquidated collateral receiver address receiver; // vault id to liquidate uint256 vaultId; // amount of debt(otoken) to repay uint256 amount; // chainlink round id uint256 roundId; } struct CallArgs { // address of the callee contract address callee; // data field for external calls bytes data; } /** * @notice parses the passed in action arguments to get the arguments for an open vault action * @param _args general action arguments structure * @return arguments for a open vault action */ function _parseOpenVaultArgs(ActionArgs memory _args) internal pure returns (OpenVaultArgs memory) { require( _args.actionType == ActionType.OpenVault, "Actions: can only parse arguments for open vault actions" ); require( _args.owner != address(0), "Actions: cannot open vault for an invalid account" ); // if not _args.data included, vault type will be 0 by default uint256 vaultType; if (_args.data.length == 32) { // decode vault type from _args.data vaultType = abi.decode(_args.data, (uint256)); } // for now we only have 2 vault types require( vaultType < 2, "Actions: cannot open vault with an invalid type" ); return OpenVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, vaultType: vaultType }); } /** * @notice parses the passed in action arguments to get the arguments for a mint action * @param _args general action arguments structure * @return arguments for a mint action */ function _parseMintArgs(ActionArgs memory _args) internal pure returns (MintArgs memory) { require( _args.actionType == ActionType.MintShortOption, "Actions: can only parse arguments for mint actions" ); require( _args.owner != address(0), "Actions: cannot mint from an invalid account" ); return MintArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a burn action * @param _args general action arguments structure * @return arguments for a burn action */ function _parseBurnArgs(ActionArgs memory _args) internal pure returns (BurnArgs memory) { require( _args.actionType == ActionType.BurnShortOption, "Actions: can only parse arguments for burn actions" ); require( _args.owner != address(0), "Actions: cannot burn from an invalid account" ); return BurnArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, otoken: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a deposit action * @param _args general action arguments structure * @return arguments for a deposit action */ function _parseDepositArgs(ActionArgs memory _args) internal pure returns (DepositArgs memory) { require( (_args.actionType == ActionType.DepositLongOption) || (_args.actionType == ActionType.DepositCollateral), "Actions: can only parse arguments for deposit actions" ); require( _args.owner != address(0), "Actions: cannot deposit to an invalid account" ); return DepositArgs({ owner: _args.owner, vaultId: _args.vaultId, from: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a withdraw action * @param _args general action arguments structure * @return arguments for a withdraw action */ function _parseWithdrawArgs(ActionArgs memory _args) internal pure returns (WithdrawArgs memory) { require( (_args.actionType == ActionType.WithdrawLongOption) || (_args.actionType == ActionType.WithdrawCollateral), "Actions: can only parse arguments for withdraw actions" ); require( _args.owner != address(0), "Actions: cannot withdraw from an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw to an invalid account" ); return WithdrawArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress, asset: _args.asset, index: _args.index, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for an redeem action * @param _args general action arguments structure * @return arguments for a redeem action */ function _parseRedeemArgs(ActionArgs memory _args) internal pure returns (RedeemArgs memory) { require( _args.actionType == ActionType.Redeem, "Actions: can only parse arguments for redeem actions" ); require( _args.secondAddress != address(0), "Actions: cannot redeem to an invalid account" ); return RedeemArgs({ receiver: _args.secondAddress, otoken: _args.asset, amount: _args.amount }); } /** * @notice parses the passed in action arguments to get the arguments for a settle vault action * @param _args general action arguments structure * @return arguments for a settle vault action */ function _parseSettleVaultArgs(ActionArgs memory _args) internal pure returns (SettleVaultArgs memory) { require( _args.actionType == ActionType.SettleVault, "Actions: can only parse arguments for settle vault actions" ); require( _args.owner != address(0), "Actions: cannot settle vault for an invalid account" ); require( _args.secondAddress != address(0), "Actions: cannot withdraw payout to an invalid account" ); return SettleVaultArgs({ owner: _args.owner, vaultId: _args.vaultId, to: _args.secondAddress }); } function _parseLiquidateArgs(ActionArgs memory _args) internal pure returns (LiquidateArgs memory) { require( _args.actionType == ActionType.Liquidate, "Actions: can only parse arguments for liquidate action" ); require( _args.owner != address(0), "Actions: cannot liquidate vault for an invalid account owner" ); require( _args.secondAddress != address(0), "Actions: cannot send collateral to an invalid account" ); require( _args.data.length == 32, "Actions: cannot parse liquidate action with no round id" ); // decode chainlink round id from _args.data uint256 roundId = abi.decode(_args.data, (uint256)); return LiquidateArgs({ owner: _args.owner, receiver: _args.secondAddress, vaultId: _args.vaultId, amount: _args.amount, roundId: roundId }); } /** * @notice parses the passed in action arguments to get the arguments for a call action * @param _args general action arguments structure * @return arguments for a call action */ function _parseCallArgs(ActionArgs memory _args) internal pure returns (CallArgs memory) { require( _args.actionType == ActionType.Call, "Actions: can only parse arguments for call actions" ); require( _args.secondAddress != address(0), "Actions: target address cannot be address(0)" ); return CallArgs({callee: _args.secondAddress, data: _args.data}); } } /** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.0; /** * @title MarginVault * @author Opyn Team * @notice A library that provides the Controller with a Vault struct and the functions that manipulate vaults. * Vaults describe discrete position combinations of long options, short options, and collateral assets that a user can have. */ library MarginVault { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } // 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 "../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 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: UNLICENSED pragma solidity 0.8.0; interface IOtoken { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
return if otoken is whitelisted on Gamma _otoken otoken address return true if isWhitelistedOtoken returns true for _otoken/
function isWhitelistedOtoken(address _otoken) public view returns (bool) { return whitelist.isWhitelistedOtoken(_otoken); }
27,796
./full_match/1/0x56356710715D2D29232D0D8784390e2a1C42514E/sources/arb-bridge-peripherals/contracts/tokenbridge/ethereum/gateway/L1GatewayRouter.sol
_gateway l1 gateway address _maxGas max gas for L2 retryable exrecution _gasPriceBid gas price for L2 retryable ticket _maxSubmissionCost base submission cost L2 retryable tick3et return Retryable ticket ID/
function setGateway( address _gateway, uint256 _maxGas, uint256 _gasPriceBid, uint256 _maxSubmissionCost ) external payable returns (uint256) { return setGateway(_gateway, _maxGas, _gasPriceBid, _maxSubmissionCost, msg.sender); }
9,736,274
// SPDX-License-Identifier: Unlicensed pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function ManageBot() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract tweet is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 private maxTransactionAmount; uint256 private swapTokensAtAmount; uint256 private maxWallet; bool private limitsInEffect = true; bool private tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 private buyTotalFees; uint256 private buyMarketingFee; uint256 private buyLiquidityFee; uint256 private buyDevFee; uint256 private sellTotalFees; uint256 private sellMarketingFee; uint256 private sellLiquidityFee; uint256 private sellDevFee; uint256 private earlySellLiquidityFee; uint256 private earlySellMarketingFee; uint256 private earlySellDevFee; uint256 private tokensForMarketing; uint256 private tokensForLiquidity; uint256 private tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("TWEET", "TWT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 5; uint256 _earlySellLiquidityFee = 5; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 5; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 20 / 1000; // 2% maxTransactionAmountTxn maxWallet = totalSupply * 50 / 1000; // 5% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function renounceOwnership (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = false; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 0; sellMarketingFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 0; sellMarketingFee = 4; sellDevFee = 2; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Send(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
exclude from paying fees or having max transaction amount
constructor() ERC20("TWEET", "TWT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 3; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 5; uint256 _earlySellLiquidityFee = 5; uint256 _earlySellMarketingFee = 5; uint256 _earlySellDevFee = 5; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
540,749
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./utils/Pausable.sol"; import "./base/CappedCrowdsale.sol"; import "./base/RefundableCrowdsale.sol"; import "./base/TokenController.sol"; /** * @title MemePreSale * @notice Meme Token Sale round one presale contract, with mincap (goal), softcap and hardcap (cap) * @dev This contract has to be finalized before refund or token claims are enabled */ contract MemePreSale is Pausable, CappedCrowdsale, RefundableCrowdsale { using SafeMath for uint256; // the token is here TokenController public memeController; // after reaching {weiRaised} >= {softCap}, there is {softCapTime} seconds until the sale closes // {softCapClose} contains the closing time //uint256 public rate = 1250; //uint256 public goal = 333 ether; uint256 public softCap = 3600 ether; uint256 public softCapTime = 120 hours; uint256 public softCapClose; //uint256 public cap = 7200 ether; // how many token is sold and not claimed, used for refunding to token controller uint256 public tokenBalance; // total token sold uint256 public tokenSold; // contributing above {maxGasPrice} results in // calculating stakes on {maxGasPricePenalty} / 100 // eg. 80 {maxGasPricePenalty} means 80%, sending 5 ETH with more than 100gwei gas price will be calculated as 4 ETH uint256 public maxGasPrice = 100 * 10**9; uint256 public maxGasPricePenalty = 80; // minimum contribution, 0.1ETH uint256 public minContribution = 0.1 ether; // first {whitelistDayCount} days of token sale is exclusive for whitelisted addresses // {whitelistDayMaxStake} contains the max stake limits per address for each whitelist sales day // {whitelist} contains who can contribute during whitelist period uint8 public whitelistDayCount; mapping (address => bool) public whitelist; mapping (uint8 => uint256) public whitelistDayMaxStake; // stakes contains contribution stake in wei // contributed ETH is calculated on 80% when sending funds with gasprice above maxGasPrice mapping (address => uint256) public stakes; // addresses of contributors to handle finalization after token sale end (refunds or token claims) address[] public contributorsKeys; // events for token purchase during sale and claiming tokens after sale event TokenClaimed(address indexed _claimer, address indexed _beneficiary, uint256 _stake, uint256 _amount); event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _stake, uint256 _amount, uint256 _participants, uint256 _weiRaised); event TokenGoalReached(); event TokenSoftCapReached(uint256 _closeTime); // whitelist events for adding days with maximum stakes and addresses event WhitelistAddressAdded(address indexed _whitelister, address indexed _beneficiary); event WhitelistAddressRemoved(address indexed _whitelister, address indexed _beneficiary); event WhitelistSetDay(address indexed _whitelister, uint8 _day, uint256 _maxStake); //////////////// // Constructor and inherited function overrides //////////////// /// @notice Constructor to create PreSale contract /// @param _memeController Address of memeController /// @param _startTime The start time of token sale in seconds. /// @param _endTime The end time of token sale in seconds. /// @param _minContribution The minimum contribution per transaction in wei (0.1 ETH) /// @param _rate Number of Meme tokens per 1 ETH /// @param _goal Minimum funding in wei, below that EVERYONE gets back ALL their /// contributions regardless of maxGasPrice penalty. /// Eg. someone contributes with 5 ETH, but gets only 4 ETH stakes because /// sending funds with gasprice over 100Gwei, he will still get back >>5 ETH<< /// in case of unsuccessful token sale /// @param _softCap Softcap in wei, reaching it ends the sale in _softCapTime seconds /// @param _softCapTime Seconds until the sale remains open after reaching _softCap /// @param _cap Maximum cap in wei, we can't raise more funds /// @param _gasPrice Maximum gas price /// @param _gasPenalty Penalty in percentage points for calculating stakes, eg. 80 means calculating /// stakes on 80% if gasprice was higher than _gasPrice /// @param _wallet Address of multisig wallet, which will get all the funds after successful sale constructor( address _memeController, uint256 _startTime, uint256 _endTime, uint256 _minContribution, uint256 _rate, uint256 _goal, uint256 _softCap, uint256 _softCapTime, uint256 _cap, uint256 _gasPrice, uint256 _gasPenalty, address payable _wallet ) CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) { // memeController must be valid require(_memeController != address(0), 'address 0'); memeController = TokenController(_memeController); // caps have to be consistent with each other require(_goal <= _softCap && _softCap <= _cap); softCap = _softCap; softCapTime = _softCapTime; // this is needed since super constructor wont overwite overriden variables cap = _cap; goal = _goal; rate = _rate; maxGasPrice = _gasPrice; maxGasPricePenalty = _gasPenalty; minContribution = _minContribution; } function forwardFunds(uint256 weiAmount) internal override(Crowdsale, RefundableCrowdsale) { super.forwardFunds(weiAmount); } /// @dev Overriding Crowdsale#buyTokens to add partial refund and softcap logic /// @param _beneficiary Beneficiary of the token purchase function buyTokens(address _beneficiary) public payable override(Crowdsale, CappedCrowdsale) whenNotPaused { require(_beneficiary != address(0), 'Address 0'); uint256 weiToCap = howMuchCanXContributeNow(_beneficiary); uint256 weiAmount = uint256Min(weiToCap, msg.value); // goal is reached if (weiRaised < goal && weiRaised.add(weiAmount) >= goal) { emit TokenGoalReached(); } // call the Crowdsale#buyTokens internal function buyTokens(_beneficiary, weiAmount); // close sale in softCapTime seconds after reaching softCap if (weiRaised >= softCap && softCapClose == 0) { softCapClose = block.timestamp.add(softCapTime); emit TokenSoftCapReached(uint256Min(softCapClose, endTime)); } // handle refund uint256 refund = msg.value.sub(weiAmount); if (refund > 0) { payable(msg.sender).transfer(refund); } } /// @dev Overriding Crowdsale#transferToken, which keeps track of contributions DURING token sale /// @param _beneficiary Address of the recepient of the tokens /// @param _weiAmount Contribution in wei function transferToken(address _beneficiary, uint256 _weiAmount) internal override { require(_beneficiary != address(0), 'Address 0'); uint256 weiAmount = _weiAmount; // check maxGasPricePenalty if (maxGasPrice > 0 && tx.gasprice > maxGasPrice) { weiAmount = weiAmount.mul(maxGasPricePenalty).div(100); } // calculate tokens, so we can refund excess tokens to MemeController after token sale uint256 tokens = weiAmount.mul(rate); tokenBalance = tokenBalance.add(tokens); if (stakes[_beneficiary] == 0) { contributorsKeys.push(_beneficiary); } stakes[_beneficiary] = stakes[_beneficiary].add(weiAmount); emit TokenPurchase(msg.sender, _beneficiary, _weiAmount, weiAmount, tokens, contributorsKeys.length, weiRaised); } /// @dev Overriding Crowdsale#validPurchase to add min contribution logic /// @param _weiAmount Contribution amount in wei /// @return true if contribution is okay function validPurchase(uint256 _weiAmount) internal view override(Crowdsale, CappedCrowdsale) returns (bool) { return super.validPurchase(_weiAmount) && _weiAmount >= minContribution; } /// @dev Overriding Crowdsale#hasEnded to add soft cap logic /// @return true if crowdsale event has ended or a softCapClose time is set and passed function hasEnded() public view override(Crowdsale, CappedCrowdsale) returns (bool) { return super.hasEnded() || softCapClose > 0 && block.timestamp > softCapClose; } /// @dev Overriding RefundableCrowdsale#claimRefund to enable anyone to call for any address /// which enables us to refund anyone and also anyone can refund themselves function claimRefund() override public { claimRefundFor(payable(msg.sender)); } /// @dev Extending RefundableCrowdsale#finalization sending back excess tokens to memeController function finalization() internal override { uint256 _balance = getHealBalance(); // if token sale was successful send back excess funds if (goalReached()) { // saving token balance for future reference tokenSold = tokenBalance; // send back the excess token to memeController if (_balance > tokenBalance) { memeController.memeToken().transfer(memeController.SALE(), _balance.sub(tokenBalance)); } } else if (!goalReached() && _balance > 0) { // if token sale is failed, then send back all tokens to memeController's sale address tokenBalance = 0; memeController.memeToken().transfer(memeController.SALE(), _balance); } super.finalization(); } //////////////// // BEFORE token sale //////////////// /// @notice Modifier for before sale cases modifier beforeSale() { require(!hasStarted()); _; } /// @notice Sets whitelist /// @dev The length of _whitelistLimits says that the first X days of token sale is /// closed, meaning only for whitelisted addresses. /// @param _add Array of addresses to add to whitelisted ethereum accounts /// @param _remove Array of addresses to remove to whitelisted ethereum accounts /// @param _whitelistLimits Array of limits in wei, where _whitelistLimits[0] = 10 ETH means /// whitelisted addresses can contribute maximum 10 ETH stakes on the first day /// After _whitelistLimits.length days, there will be no limits per address (besides hard cap) function setWhitelist(address[] memory _add, address[] memory _remove, uint256[] memory _whitelistLimits) public onlyOwner beforeSale { uint256 i = 0; uint8 j = 0; // access max daily stakes // we override whiteListLimits only if it was supplied as an argument if (_whitelistLimits.length > 0) { // saving whitelist max stake limits for each day -> uint256 maxStakeLimit whitelistDayCount = uint8(_whitelistLimits.length); for (i = 0; i < _whitelistLimits.length; i++) { j = uint8(i.add(1)); if (whitelistDayMaxStake[j] != _whitelistLimits[i]) { whitelistDayMaxStake[j] = _whitelistLimits[i]; emit WhitelistSetDay(msg.sender, j, _whitelistLimits[i]); } } } // adding whitelist addresses for (i = 0; i < _add.length; i++) { require(_add[i] != address(0)); if (!whitelist[_add[i]]) { whitelist[_add[i]] = true; emit WhitelistAddressAdded(msg.sender, _add[i]); } } // removing whitelist addresses for (i = 0; i < _remove.length; i++) { require(_remove[i] != address(0)); if (whitelist[_remove[i]]) { whitelist[_remove[i]] = false; emit WhitelistAddressRemoved(msg.sender, _remove[i]); } } } /// @notice Sets max gas price and penalty before sale function setMaxGas(uint256 _maxGas, uint256 _penalty) public onlyOwner beforeSale { maxGasPrice = _maxGas; maxGasPricePenalty = _penalty; } /// @notice Sets min contribution before sale function setMinContribution(uint256 _minContribution) public onlyOwner beforeSale { minContribution = _minContribution; } /// @notice Sets minimum goal, soft cap and max cap function setCaps(uint256 _goal, uint256 _softCap, uint256 _softCapTime, uint256 _cap) public onlyOwner beforeSale { require(0 < _goal && _goal <= _softCap && _softCap <= _cap, "0 < _goal && _goal <= _softCap && _softCap <= _cap"); goal = _goal; softCap = _softCap; softCapTime = _softCapTime; cap = _cap; } /// @notice Sets crowdsale start and end time function setTimes(uint256 _startTime, uint256 _endTime) public onlyOwner beforeSale { require(_startTime > block.timestamp && _startTime < _endTime, "_startTime > block.timestamp && _startTime < _endTime"); startTime = _startTime; endTime = _endTime; } /// @notice Set rate function setRate(uint256 _rate) public onlyOwner beforeSale { require(_rate > 0); rate = _rate; } //////////////// // AFTER token sale //////////////// /// @notice Modifier for cases where sale is failed /// @dev It checks whether we haven't reach the minimum goal AND whether the contract is finalized modifier afterSaleFail() { require(!goalReached() && isFinalized); _; } /// @notice Modifier for cases where sale is closed and was successful. /// @dev It checks whether /// the sale has ended /// and we have reached our goal /// AND whether the contract is finalized modifier afterSaleSuccess() { require(goalReached() && isFinalized); _; } /// @notice Modifier for after sale finalization modifier afterSale() { require(isFinalized); _; } /// @notice Refund an ethereum address /// @param _beneficiary Address we want to refund function claimRefundFor(address payable _beneficiary) public afterSaleFail whenNotPaused { require(_beneficiary != address(0)); vault.refund(_beneficiary); } /// @notice Refund several addresses with one call /// @param _beneficiaries Array of addresses we want to refund function claimRefundsFor(address payable[] calldata _beneficiaries) external afterSaleFail { for (uint256 i = 0; i < _beneficiaries.length; i++) { claimRefundFor(_beneficiaries[i]); } } /// @notice Claim token for msg.sender after token sale based on stake. function claimToken() public afterSaleSuccess { claimTokenFor(msg.sender); } /// @notice Claim token after token sale based on stake. /// @dev Anyone can call this function and distribute tokens after successful token sale /// @param _beneficiary Address of the beneficiary who gets the token function claimTokenFor(address _beneficiary) public afterSaleSuccess whenNotPaused { uint256 stake = stakes[_beneficiary]; require(stake > 0); // set the stake 0 for beneficiary stakes[_beneficiary] = 0; // calculate token count uint256 tokens = stake.mul(rate); // decrease tokenBalance, to make it possible to withdraw excess HEAL funds tokenBalance = tokenBalance.sub(tokens); // distribute hodlr stake memeController.addHodlerStake(_beneficiary, tokens.mul(2)); // distribute token require(memeController.memeToken().transfer(_beneficiary, tokens)); emit TokenClaimed(msg.sender, _beneficiary, stake, tokens); } /// @notice claimToken() for multiple addresses /// @dev Anyone can call this function and distribute tokens after successful token sale /// @param _beneficiaries Array of addresses for which we want to claim tokens function claimTokensFor(address[] calldata _beneficiaries) external afterSaleSuccess { for (uint256 i = 0; i < _beneficiaries.length; i++) { claimTokenFor(_beneficiaries[i]); } } /// @notice Get back accidentally sent token from the vault function extractVaultTokens(address _token, address payable _claimer) public onlyOwner afterSale { // it has to have a valid claimer, and either the goal has to be reached or the token can be 0 which means we can't extract ether if the goal is not reached require(_claimer != address(0)); require(goalReached() || _token != address(0)); vault.extractTokens(_token, _claimer); } //////////////// // Constant, helper functions //////////////// /// @notice How many wei can the msg.sender contribute now. function howMuchCanIContributeNow() payable public returns (uint256) { return howMuchCanXContributeNow(msg.sender); } /// @notice How many wei can an ethereum address contribute now. /// @dev This function can return 0 when the crowdsale is stopped /// or the address has maxed the current day's whitelist cap, /// it is possible, that next day he can contribute /// @param _beneficiary Ethereum address /// @return Number of wei the _beneficiary can contribute now. function howMuchCanXContributeNow(address _beneficiary) public payable returns (uint256) { require(_beneficiary != address(0)); if (!hasStarted() || hasEnded()) { return 0; } // wei to hard cap uint256 weiToCap = cap.sub(weiRaised); // if this is a whitelist limited period uint8 _saleDay = getSaleDayNow(); if (_saleDay <= whitelistDayCount) { // address can't contribute if // it is not whitelisted if (!whitelist[_beneficiary]) { return 0; } // personal cap is the daily whitelist limit minus the stakes the address already has uint256 weiToPersonalCap = whitelistDayMaxStake[_saleDay].sub(stakes[_beneficiary]); // calculate for maxGasPrice penalty if (msg.value > 0 && maxGasPrice > 0 && tx.gasprice > maxGasPrice) { weiToPersonalCap = weiToPersonalCap.mul(100).div(maxGasPricePenalty); } weiToCap = uint256Min(weiToCap, weiToPersonalCap); } return weiToCap; } /// @notice For a give date how many 24 hour blocks have ellapsed since token sale start /// @dev _time has to be bigger than the startTime of token sale, otherwise SafeMath's div will throw. /// Within 24 hours of token sale it will return 1, /// between 24 and 48 hours it will return 2, etc. /// @param _time Date in seconds for which we want to know which sale day it is /// @return Number of 24 hour blocks ellapsing since token sale start starting from 1 function getSaleDay(uint256 _time) view public returns (uint8) { return uint8(_time.sub(startTime).div(60*60*24).add(1)); } /// @notice How many 24 hour blocks have ellapsed since token sale start /// @return Number of 24 hour blocks ellapsing since token sale start starting from 1 function getSaleDayNow() view public returns (uint8) { return getSaleDay(block.timestamp); } /// @notice Minimum between two uint8 numbers function uint8Min(uint8 a, uint8 b) pure internal returns (uint8) { return a > b ? b : a; } /// @notice Minimum between two uint256 numbers function uint256Min(uint256 a, uint256 b) pure internal returns (uint256) { return a > b ? b : a; } //////////////// // Test and contribution web app, NO audit is needed //////////////// /// @notice Was this token sale successful? /// @return true if the sale is over and we have reached the minimum goal function wasSuccess() view public returns (bool) { return hasEnded() && goalReached(); } /// @notice How many contributors we have. /// @return Number of different contributor ethereum addresses function getContributorsCount() view public returns (uint256) { return contributorsKeys.length; } /// @notice Get contributor addresses to manage refunds or token claims. /// @dev If the sale is not yet successful, then it searches in the RefundVault. /// If the sale is successful, it searches in contributors. /// @param _pending If true, then returns addresses which didn't get refunded or their tokens distributed to them /// @param _claimed If true, then returns already refunded or token distributed addresses /// @return contributors Array of addresses of contributors function getContributors(bool _pending, bool _claimed) view public returns (address[] memory contributors) { uint256 i = 0; uint256 results = 0; address[] memory _contributors = new address[](contributorsKeys.length); // if we have reached our goal, then search in contributors, since this is what we want to monitor if (goalReached()) { for (i = 0; i < contributorsKeys.length; i++) { if (_pending && stakes[contributorsKeys[i]] > 0 || _claimed && stakes[contributorsKeys[i]] == 0) { _contributors[results] = contributorsKeys[i]; results++; } } } else { // otherwise search in the refund vault for (i = 0; i < contributorsKeys.length; i++) { if (_pending && vault.deposited(contributorsKeys[i]) > 0 || _claimed && vault.deposited(contributorsKeys[i]) == 0) { _contributors[results] = contributorsKeys[i]; results++; } } } contributors = new address[](results); for (i = 0; i < results; i++) { contributors[i] = _contributors[i]; } return contributors; } /// @notice How many HEAL tokens do this contract have function getHealBalance() view public returns (uint256) { return memeController.memeToken().balanceOf(address(this)); } /// @notice Get current date for web3 function getNow() view public returns (uint256) { return block.timestamp; } }
Sets whitelist The length of _whitelistLimits says that the first X days of token sale is closed, meaning only for whitelisted addresses. _add Array of addresses to add to whitelisted ethereum accounts _remove Array of addresses to remove to whitelisted ethereum accounts _whitelistLimits Array of limits in wei, where _whitelistLimits[0] = 10 ETH means whitelisted addresses can contribute maximum 10 ETH stakes on the first day After _whitelistLimits.length days, there will be no limits per address (besides hard cap) we override whiteListLimits only if it was supplied as an argument saving whitelist max stake limits for each day -> uint256 maxStakeLimit adding whitelist addresses removing whitelist addresses
function setWhitelist(address[] memory _add, address[] memory _remove, uint256[] memory _whitelistLimits) public onlyOwner beforeSale { uint256 i = 0; if (_whitelistLimits.length > 0) { whitelistDayCount = uint8(_whitelistLimits.length); for (i = 0; i < _whitelistLimits.length; i++) { j = uint8(i.add(1)); if (whitelistDayMaxStake[j] != _whitelistLimits[i]) { whitelistDayMaxStake[j] = _whitelistLimits[i]; emit WhitelistSetDay(msg.sender, j, _whitelistLimits[i]); } } } for (i = 0; i < _add.length; i++) { require(_add[i] != address(0)); if (!whitelist[_add[i]]) { whitelist[_add[i]] = true; emit WhitelistAddressAdded(msg.sender, _add[i]); } } for (i = 0; i < _remove.length; i++) { require(_remove[i] != address(0)); if (whitelist[_remove[i]]) { whitelist[_remove[i]] = false; emit WhitelistAddressRemoved(msg.sender, _remove[i]); } } }
6,444,806
./full_match/3/0xa0826607DBc6345EC7757C25cdd946965e97Ad7A/sources/contracts/elections.sol
this function sets the state to Created. this function indicates the start of the election./
function startVote() public inState(State.Created) onlyOwner { state = State.Voting; } the owner cannot vote. Specifies the address the voter voted for, and sets the flag to indicate that the voter has now voted. It increments the candidate's vote count and the total vote count.
8,182,857
//Address: 0x5db2d4a2e6d06f9afe906fc33036f77ebe87b59b //Contract name: GizerToken //Balance: 0 Ether //Verification Date: 2/15/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.19; // ---------------------------------------------------------------------------- // // GZR 'Gizer Gaming' token public sale contract // // For details, please visit: http://www.gizer.io // // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // // SafeMath (division not needed) // // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require( c >= a ); } function sub(uint a, uint b) internal pure returns (uint c) { require( b <= a ); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require( a == 0 || c / a == b ); } } // ---------------------------------------------------------------------------- // // Owned contract // // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; // Events --------------------------- event OwnershipTransferProposed(address indexed _from, address indexed _to); event OwnershipTransferred(address indexed _to); // Modifier ------------------------- modifier onlyOwner { require( msg.sender == owner ); _; } // Functions ------------------------ function Owned() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { require( _newOwner != owner ); require( _newOwner != address(0x0) ); newOwner = _newOwner; OwnershipTransferProposed(owner, _newOwner); } function acceptOwnership() public { require( msg.sender == newOwner ); owner = newOwner; OwnershipTransferred(owner); } } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // // ---------------------------------------------------------------------------- contract ERC20Interface { // Events --------------------------- event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); // Functions ------------------------ function totalSupply() public view returns (uint); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); } // ---------------------------------------------------------------------------- // // ERC Token Standard #20 // // ---------------------------------------------------------------------------- contract ERC20Token is ERC20Interface, Owned { using SafeMath for uint; uint public tokensIssuedTotal = 0; mapping(address => uint) balances; mapping(address => mapping (address => uint)) allowed; // Functions ------------------------ /* Total token supply */ function totalSupply() public view returns (uint) { return tokensIssuedTotal; } /* Get the account balance for an address */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /* Transfer the balance from owner's account to another account */ function transfer(address _to, uint _amount) public returns (bool success) { // amount sent cannot exceed balance require( balances[msg.sender] >= _amount ); // update balances balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); // log event Transfer(msg.sender, _to, _amount); return true; } /* Allow _spender to withdraw from your account up to _amount */ function approve(address _spender, uint _amount) public returns (bool success) { // approval amount cannot exceed the balance require( balances[msg.sender] >= _amount ); // update allowed amount allowed[msg.sender][_spender] = _amount; // log event Approval(msg.sender, _spender, _amount); return true; } /* Spender of tokens transfers tokens from the owner's balance */ /* Must be pre-approved by owner */ function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { // balance checks require( balances[_from] >= _amount ); require( allowed[_from][msg.sender] >= _amount ); // update balances and allowed amount balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); // log event Transfer(_from, _to, _amount); return true; } /* Returns the amount of tokens approved by the owner */ /* that can be transferred by spender */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } // ---------------------------------------------------------------------------- // // GZR public token sale // // ---------------------------------------------------------------------------- contract GizerToken is ERC20Token { /* Utility variable */ uint constant E6 = 10**6; /* Basic token data */ string public constant name = "Gizer Gaming Token"; string public constant symbol = "GZR"; uint8 public constant decimals = 6; /* Wallets */ address public wallet; address public redemptionWallet; /* Crowdsale parameters (constants) */ uint public constant DATE_ICO_START = 1518962400; // 18-Feb-2018 14:00 UTC 09:00 EST uint public constant DATE_ICO_END = 1521122400; // 15-Mar-2018 14:00 UTC 10:00 EST uint public constant TOKEN_SUPPLY_TOTAL = 10000000 * E6; uint public constant TOKEN_SUPPLY_CROWD = 6112926 * E6; uint public constant TOKEN_SUPPLY_OWNER = 3887074 * E6; // 2,000,000 tokens reserve // 1,887,074 presale tokens uint public constant MIN_CONTRIBUTION = 1 ether / 100; uint public constant TOKENS_PER_ETH = 1000; uint public constant DATE_TOKENS_UNLOCKED = 1537020000; // 15-SEP-2018 14:00 UTC 10:00 EST /* Crowdsale variables */ uint public tokensIssuedCrowd = 0; uint public tokensIssuedOwner = 0; uint public tokensIssuedLocked = 0; uint public etherReceived = 0; // does not include presale ethers /* Keep track of + ethers contributed, + tokens received + tokens locked during Crowdsale */ mapping(address => uint) public etherContributed; mapping(address => uint) public tokensReceived; mapping(address => uint) public locked; // Events --------------------------- event WalletUpdated(address _newWallet); event RedemptionWalletUpdated(address _newRedemptionWallet); event EthCentsUpdated(uint _cents); event TokensIssuedCrowd(address indexed _recipient, uint _tokens, uint _ether); event TokensIssuedOwner(address indexed _recipient, uint _tokens, bool _locked); // Basic Functions ------------------ /* Initialize */ function GizerToken() public { require( TOKEN_SUPPLY_OWNER + TOKEN_SUPPLY_CROWD == TOKEN_SUPPLY_TOTAL ); wallet = owner; redemptionWallet = owner; } /* Fallback */ function () public payable { buyTokens(); } // Information Functions ------------ /* What time is it? */ function atNow() public view returns (uint) { return now; } /* Are tokens tradeable */ function tradeable() public view returns (bool) { if (atNow() > DATE_ICO_END) return true ; return false; } /* Available to mint by owner */ function availableToMint() public view returns (uint available) { if (atNow() <= DATE_ICO_END) { available = TOKEN_SUPPLY_OWNER.sub(tokensIssuedOwner); } else { available = TOKEN_SUPPLY_TOTAL.sub(tokensIssuedTotal); } } /* Unlocked tokens in an account */ function unlockedTokens(address _account) public view returns (uint _unlockedTokens) { if (atNow() <= DATE_TOKENS_UNLOCKED) { return balances[_account] - locked[_account]; } else { return balances[_account]; } } // Owner Functions ------------------ /* Change the crowdsale wallet address */ function setWallet(address _wallet) public onlyOwner { require( _wallet != address(0x0) ); wallet = _wallet; WalletUpdated(_wallet); } /* Change the redemption wallet address */ function setRedemptionWallet(address _wallet) public onlyOwner { require( _wallet != address(0x0) ); redemptionWallet = _wallet; RedemptionWalletUpdated(_wallet); } /* Minting of tokens by owner */ function mintTokens(address _account, uint _tokens) public onlyOwner { // check token amount require( _tokens <= availableToMint() ); // update balances[_account] = balances[_account].add(_tokens); tokensIssuedOwner = tokensIssuedOwner.add(_tokens); tokensIssuedTotal = tokensIssuedTotal.add(_tokens); // log event Transfer(0x0, _account, _tokens); TokensIssuedOwner(_account, _tokens, false); } /* Minting of tokens by owner */ function mintTokensLocked(address _account, uint _tokens) public onlyOwner { // check token amount require( _tokens <= availableToMint() ); // update balances[_account] = balances[_account].add(_tokens); locked[_account] = locked[_account].add(_tokens); tokensIssuedOwner = tokensIssuedOwner.add(_tokens); tokensIssuedTotal = tokensIssuedTotal.add(_tokens); tokensIssuedLocked = tokensIssuedLocked.add(_tokens); // log event Transfer(0x0, _account, _tokens); TokensIssuedOwner(_account, _tokens, true); } /* Transfer out any accidentally sent ERC20 tokens */ function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, amount); } // Private functions ---------------- /* Accept ETH during crowdsale (called by default function) */ function buyTokens() private { // basic checks require( atNow() > DATE_ICO_START && atNow() < DATE_ICO_END ); require( msg.value >= MIN_CONTRIBUTION ); // check token volume uint tokensAvailable = TOKEN_SUPPLY_CROWD.sub(tokensIssuedCrowd); uint tokens = msg.value.mul(TOKENS_PER_ETH) / 10**12; require( tokens <= tokensAvailable ); // issue tokens balances[msg.sender] = balances[msg.sender].add(tokens); // update global tracking variables tokensIssuedCrowd = tokensIssuedCrowd.add(tokens); tokensIssuedTotal = tokensIssuedTotal.add(tokens); etherReceived = etherReceived.add(msg.value); // update contributor tracking variables etherContributed[msg.sender] = etherContributed[msg.sender].add(msg.value); tokensReceived[msg.sender] = tokensReceived[msg.sender].add(tokens); // transfer Ether out if (this.balance > 0) wallet.transfer(this.balance); // log token issuance TokensIssuedCrowd(msg.sender, tokens, msg.value); Transfer(0x0, msg.sender, tokens); } // ERC20 functions ------------------ /* Override "transfer" */ function transfer(address _to, uint _amount) public returns (bool success) { require( tradeable() ); require( unlockedTokens(msg.sender) >= _amount ); return super.transfer(_to, _amount); } /* Override "transferFrom" */ function transferFrom(address _from, address _to, uint _amount) public returns (bool success) { require( tradeable() ); require( unlockedTokens(_from) >= _amount ); return super.transferFrom(_from, _to, _amount); } // Bulk token transfer function ----- /* Multiple token transfers from one address to save gas */ function transferMultiple(address[] _addresses, uint[] _amounts) external { require( tradeable() ); require( _addresses.length == _amounts.length ); require( _addresses.length <= 100 ); uint i; // check token amounts uint tokens_to_transfer = 0; for (i = 0; i < _addresses.length; i++) { tokens_to_transfer = tokens_to_transfer.add(_amounts[i]); } require( tokens_to_transfer <= unlockedTokens(msg.sender) ); // do the transfers for (i = 0; i < _addresses.length; i++) { super.transfer(_addresses[i], _amounts[i]); } } }
check token amounts do the transfers
function transferMultiple(address[] _addresses, uint[] _amounts) external { require( tradeable() ); require( _addresses.length == _amounts.length ); require( _addresses.length <= 100 ); uint i; uint tokens_to_transfer = 0; for (i = 0; i < _addresses.length; i++) { tokens_to_transfer = tokens_to_transfer.add(_amounts[i]); } require( tokens_to_transfer <= unlockedTokens(msg.sender) ); for (i = 0; i < _addresses.length; i++) { super.transfer(_addresses[i], _amounts[i]); } }
1,001,682
./full_match/11155111/0x274F2B629E8AB1b5606a78428976c5cA867e8155/sources/src/SimpleStorage.sol
function that stores and updates myFavoriteNumber.... Hint: Everytime you updates the state of a blockchain, is going to cost gas.
function store(uint256 _favoriteNumber) public { myFavoriteNumber = _favoriteNumber; }
3,801,131
// SPDX-License-Identifier: MIT pragma solidity 0.5.17; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-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 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 IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } contract BetaCarbon is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; bool public paused = false; // ASSET PROTECTION DATA address public assetProtectionRole; mapping(address => bool) internal frozen; // SUPPLY CONTROL DATA address public supplyController; // OWNER DATA address public owner; address public proposedOwner; bool public initialized = false; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("BetaCarbon", "BCAU", 18) { initialize(); _mint(0); pause(); } function initialize() public { require(!initialized, "already initialized"); owner = msg.sender; proposedOwner = address(0); assetProtectionRole = address(0); supplyController = msg.sender; initialized = true; } // OWNABLE EVENTS event OwnershipTransferProposed( address indexed currentOwner, address indexed proposedOwner ); event OwnershipTransferDisregarded(address indexed oldProposedOwner); event OwnershipTransferred( address indexed oldOwner, address indexed newOwner ); // PAUSABLE EVENTS event Pause(); event Unpause(); // ASSET PROTECTION EVENTS event AddressFrozen(address indexed addr); event AddressUnfrozen(address indexed addr); event FrozenAddressWiped(address indexed addr); event AssetProtectionRoleSet( address indexed oldAssetProtectionRole, address indexed newAssetProtectionRole ); // SUPPLY CONTROL EVENTS event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController ); /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param me The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address me) public view returns (uint256) { return _balances[me]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param me 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 me, address spender) public view returns (uint256) { return _allowed[me][spender]; } modifier whenNotPaused() { require(!paused, "whenNotPaused"); _; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public whenNotPaused returns (bool) { require(to != address(0), "cannot transfer to address zero"); require(!frozen[to] && !frozen[msg.sender], "address frozen"); require(value <= _balances[msg.sender], "insufficient funds"); _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(to != address(0), "cannot transfer to address zero"); require( !frozen[to] && !frozen[from] && !frozen[msg.sender], "address frozen" ); require(value <= _balances[from], "insufficient funds"); require(value <= _allowed[from][msg.sender], "insufficient allowance"); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); //_approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "cannot transfer to address zero"); require(value <= _balances[from], "insufficient funds"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Approve an address to spend another addresses' tokens. * @param me The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address me, address spender, uint256 value) internal { require(spender != address(0)); require(me != address(0)); _allowed[me][spender] = value; emit Approval(me, spender, value); } modifier onlySupplyController() { require(msg.sender == supplyController, "onlySupplyController"); _; } /** * @dev Function to mint tokens * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(uint256 value) public onlySupplyController returns (bool) { _mint(value); return true; } /** * @dev Function to burn tokens * @param value The amount that will be burnt. * @return A boolean that indicates if the operation was successful. */ function burn(uint256 value) public onlySupplyController returns (bool) { _burn(value); return true; } /** * @dev Increases the total supply by minting the specified number of tokens to the supply controller account. * @param _value The number of tokens to add. * @return A boolean that indicates if the operation was successful. */ function _mint(uint256 _value) internal onlySupplyController returns (bool success) { _totalSupply = _totalSupply.add(_value); _balances[supplyController] = _balances[supplyController].add(_value); emit SupplyIncreased(supplyController, _value); emit Transfer(address(0), supplyController, _value); return true; } /** * @dev Decrease the total supply by burning the specified number of tokens to the supply controller account. * @param _value The number of tokens to burn. * @return A boolean that indicates if the operation was successful. */ function _burn(uint256 _value) internal onlySupplyController returns (bool success) { require(_value <= _balances[supplyController], "not enough supply"); //_value = _value* 10**18; _balances[supplyController] = _balances[supplyController].sub(_value); _totalSupply = _totalSupply.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; } modifier onlyOwner() { require(msg.sender == owner, "onlyOwner"); _; } function pause() public onlyOwner { require(!paused, "already paused"); paused = true; emit Pause(); } function unpause() public onlyOwner { require(paused, "already unpaused"); paused = false; emit Unpause(); } /** * @dev Allows the current owner to begin transferring control of the contract to a proposedOwner * @param _proposedOwner The address to transfer ownership to. */ function proposeOwner(address _proposedOwner) public onlyOwner { require( _proposedOwner != address(0), "cannot transfer ownership to address zero" ); require(msg.sender != _proposedOwner, "caller already is owner"); proposedOwner = _proposedOwner; emit OwnershipTransferProposed(owner, proposedOwner); } /** * @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner commented out since this is not used */ function disregardProposeOwner() public { require( msg.sender == proposedOwner || msg.sender == owner, "only proposedOwner or owner" ); require( proposedOwner != address(0), "can only disregard a proposed owner that was previously set" ); address _oldProposedOwner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferDisregarded(_oldProposedOwner); } /** * @dev Allows the proposed owner to complete transferring control of the contract to the proposedOwner. */ function claimOwnership() public { require(msg.sender == proposedOwner, "onlyProposedOwner"); address _oldOwner = owner; owner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferred(_oldOwner, owner); } // ASSET PROTECTION FUNCTIONALITY /** * @dev Sets a new asset protection role address. * @param _newAssetProtectionRole The new address allowed to freeze/unfreeze addresses and seize their tokens. */ function setAssetProtectionRole(address _newAssetProtectionRole) public { require( msg.sender == assetProtectionRole || msg.sender == owner, "only assetProtectionRole or Owner" ); emit AssetProtectionRoleSet( assetProtectionRole, _newAssetProtectionRole ); assetProtectionRole = _newAssetProtectionRole; } modifier onlyAssetProtectionRole() { require(msg.sender == assetProtectionRole, "onlyAssetProtectionRole"); _; } /** * @dev Freezes an address balance from being transferred. * @param _addr The new address to freeze. */ function freeze(address _addr) public onlyAssetProtectionRole { require(!frozen[_addr], "address already frozen"); frozen[_addr] = true; emit AddressFrozen(_addr); } /** * @dev Unfreezes an address balance allowing transfer. * @param _addr The new address to unfreeze. */ function unfreeze(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address already unfrozen"); frozen[_addr] = false; emit AddressUnfrozen(_addr); } /** * @dev Wipes the balance of a frozen address, burning the tokens * and setting the approval to zero. * @param _addr The new frozen address to wipe. */ function wipeFrozenAddress(address _addr) public onlyAssetProtectionRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = _balances[_addr]; _balances[_addr] = 0; _totalSupply = _totalSupply.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); } /** * @dev Gets whether the address is currently frozen. * @param _addr The address to check if frozen. * @return A bool representing whether the given address is frozen. */ function isFrozen(address _addr) public view returns (bool) { return frozen[_addr]; } // SUPPLY CONTROL FUNCTIONALITY /** * @dev Sets a new supply controller address. * @param _newSupplyController The address allowed to burn/mint tokens to control supply. */ function setSupplyController(address _newSupplyController) public { require( msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner" ); require( _newSupplyController != address(0), "cannot set supply controller to address zero" ); emit SupplyControllerSet(supplyController, _newSupplyController); supplyController = _newSupplyController; } }
Gets the balance of the specified address. me The address to query the balance of. return An uint256 representing the amount owned by the passed address./
function balanceOf(address me) public view returns (uint256) { return _balances[me]; }
12,169,998
// SPDX-License-Identifier: MIT // Creator: Mai of Tessera Labs // Special Thanks to Diversity from Divine Anarchy for all his help reviewing pragma solidity ^0.8.12; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev 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); } } } } interface ERC721TokenReceiver { function onERC721Received(address operator,address from, uint256 id, bytes calldata data) external returns (bytes4); } /** * Built to optimize for lower gas during batch mints and transfers. * A new locking mechanism has been added to protect users from all attempted scams. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * */ abstract contract ERC721L { using Address for address; using Strings for uint256; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Locked(address indexed owner, uint256 unlockCooldown); event Unlocked(address indexed owner, uint256 unlockTimestamp); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); struct addressData { uint64 balance; uint64 lockedUnlockTimestamp; uint64 lockedUnlockCooldown; bool locked; } struct collectionData { string name; string symbol; uint256 index; uint256 burned; } address private _contractOwner; collectionData internal _collectionData; mapping(uint256 => address) internal _ownerships; mapping(address => addressData) internal _addressData; mapping(uint256 => address) internal _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory _name, string memory _symbol) { _collectionData.name = _name; _collectionData.symbol = _symbol; _transferOwnership(_msgSender()); } function _msgSender() internal view virtual returns (address) { return msg.sender; } /** * @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` or `_safeMint`), */ function _exists(uint256 tokenId) public view virtual returns (bool) { return tokenId < _collectionData.index; } /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) public view virtual returns (address) { unchecked { if (tokenId < _collectionData.index) { address ownership = _ownerships[tokenId]; if (ownership != address(0)) { return ownership; } while (true) { tokenId--; ownership = _ownerships[tokenId]; if (ownership != address(0)) { return ownership; } } } } revert (); } /** * @dev Returns the number of tokens in `_owner`'s account. */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0), "Address 0"); return uint256(_addressData[_owner].balance); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { require(to != address(0), "Address 0"); require(quantity > 0, "Quantity 0"); unchecked { uint256 updatedIndex = _collectionData.index; _addressData[to].balance += uint64(quantity); _ownerships[updatedIndex] = to; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex++); } _collectionData.index = updatedIndex; } } /** * @dev See Below {ERC721L-_safeMint}. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {onERC721Received}, which is called for each safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 quantity, bytes memory _data) internal { require(to != address(0), "Address 0"); require(quantity > 0, "Quantity 0"); unchecked { uint256 updatedIndex = _collectionData.index; _addressData[to].balance += uint64(quantity); _ownerships[updatedIndex] = to; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), updatedIndex, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); updatedIndex++; } _collectionData.index = updatedIndex; } } /** * @dev Returns whether `_owner`'s tokens are currently unlocked. */ function isUnlocked(address _owner) public view returns (bool) { return !_addressData[_owner].locked && _addressData[_owner].lockedUnlockTimestamp < block.timestamp; } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - `from` must not have tokens locked. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) public virtual { address currentOwner = ownerOf(tokenId); require(isUnlocked(from), "ERC721L: Tokens Locked"); require((_msgSender() == currentOwner || getApproved(tokenId) == _msgSender() || isApprovedForAll(currentOwner,_msgSender())), "ERC721L: Not Approved"); require(currentOwner == from, "ERC721L: Not Owner"); require(to != address(0), "ERC721L: Address 0"); delete _tokenApprovals[tokenId]; unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = to; uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = currentOwner; } } emit Transfer(from, to, tokenId); } /** * @dev See Below {ERC721L-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual { safeTransferFrom(from, to, tokenId, ''); } /** * @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 {ERC721TokenReceiver}, which is called upon a safe transfer. * - `from` must not have tokens locked. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual { transferFrom(from, to, tokenId); require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), tokenId, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); } /** * @dev Batch transfers `quantity` tokens sequentially starting at `startID` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `startID` token and all sequential tokens must exist and be owned by `from`. * - `from` must not have tokens locked. * * Emits `quantity` number of {Transfer} events. */ function batchTransferFrom(address from, address to, uint256 startID, uint256 quantity) public virtual { _batchTransferFrom(from, to, startID, quantity, false, ''); } /** * @dev See Below {ERC721L-batchSafeTransferFrom}. */ function batchSafeTransferFrom(address from, address to, uint256 startID, uint256 quantity) public virtual { batchSafeTransferFrom(from, to, startID, quantity, ''); } /** * @dev Safely batch transfers `quantity` tokens sequentially starting at `startID` 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. * - `startID` token and all sequential tokens 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 {ERC721TokenReceiver}, which is called upon a safe transfer. * - `from` must not have tokens locked. * * Emits `quantity` number of {Transfer} events. */ function batchSafeTransferFrom(address from, address to, uint256 startID, uint256 quantity, bytes memory _data) public virtual { _batchTransferFrom(from, to, startID, quantity, true, _data); } function _batchTransferFrom (address from, address to, uint256 startID, uint256 quantity, bool safe, bytes memory _data) internal { require(isUnlocked(from), "ERC721L: Tokens Locked"); require(_msgSender() == from || isApprovedForAll(from,_msgSender()), "ERC721L: Not Approved"); require(multiOwnerCheck(from, startID, quantity), "ERC721L: Not Batchable"); require(to != address(0), "ERC721L: Address 0"); unchecked { for (uint256 i; i < quantity; i++) { uint256 currentToken = startID + i; delete _tokenApprovals[currentToken]; if (i == 0){ _ownerships[currentToken] = to; } else { delete _ownerships[currentToken]; } emit Transfer(from, to, currentToken); if (safe){ require(to.code.length == 0 || ERC721TokenReceiver(to).onERC721Received(_msgSender(), address(0), currentToken, _data) == ERC721TokenReceiver.onERC721Received.selector, "Unsafe Destination"); } } _addressData[from].balance -= uint64(quantity); _addressData[to].balance += uint64(quantity); uint256 nextTokenId = startID + quantity; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = from; } } } /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() public view returns (uint256) { unchecked { return _collectionData.index - _collectionData.burned; } } /** * @dev Returns the total amount of tokens created by the contract. */ function totalCreated() public view returns (uint256) { return _collectionData.index; } /** * @dev Returns the total amount of tokens burned by the contract. */ function totalBurned() public view returns (uint256) { return _collectionData.burned; } /** * @dev Returns whether `_addressToCheck` is the owner of `quantity` tokens sequentially starting from `startID`. * * Requirements: * * - `startID` token and all sequential tokens must exist. */ function multiOwnerCheck(address _addressToCheck, uint256 startID, uint256 quantity) internal view returns (bool) { require(quantity > 1, "Low Quantity"); unchecked { for (uint256 i; i < quantity; i++) { if (ownerOf(startID + i) != _addressToCheck){ return false; } } } return true; } /** * @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. * - Owner must not have tokens locked. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) public { require(operator != _msgSender(), "ERC721L: Address is Owner"); require(isUnlocked(_msgSender()), "ERC721L: Tokens Locked"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev Returns if the `operator` is allowed to manage all of the assets of `_owner` and tokens are unlocked for `_owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address _owner, address operator) public view returns (bool) { return !isUnlocked(_owner) ? false : _operatorApprovals[_owner][operator]; } /** * @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) public { address tokenOwner = ownerOf(tokenId); require(_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()), "ERC721L: Not Approved"); _tokenApprovals[tokenId] = to; emit Approval(tokenOwner, to, tokenId); } /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721L: Null ID"); return _tokenApprovals[tokenId]; } /** * @dev Locks `_owner`'s tokens from any form of transferring. * Requirements: * * - The `caller` cannot have their tokens locked currently. * * Emits a {Locked} event. */ function lock(uint256 _cooldown) public { require(!_addressData[_msgSender()].locked, "Tokens currently locked"); require(_cooldown > 0 && _cooldown < 31, "Invalid Cooldown"); unchecked { uint256 proposedCooldown = _cooldown * 1 days; require(block.timestamp + proposedCooldown > _addressData[_msgSender()].lockedUnlockTimestamp, "Proposed cooldown too small"); _addressData[_msgSender()].locked = true; _addressData[_msgSender()].lockedUnlockCooldown = uint64(proposedCooldown); } emit Locked(_msgSender(), _cooldown); } /** * @dev Begins unlocking process for `_owner`'s tokens. * Requirements: * * - The `caller` cannot have their tokens unlocked currently. * * Emits an {Unlocked} event. */ function unlock() public { require(_addressData[_msgSender()].locked, "Tokens currently unlocked"); delete _addressData[_msgSender()].locked; unchecked { _addressData[_msgSender()].lockedUnlockTimestamp = uint64(block.timestamp + _addressData[_msgSender()].lockedUnlockCooldown); } emit Unlocked(_msgSender(), block.timestamp); } /** * @dev Returns the token collection name. */ function name() public view returns (string memory) { return _collectionData.name; } /** * @dev Returns the token collection symbol. */ function symbol() public view returns (string memory) { return _collectionData.symbol; } /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), "ERC721L: Null ID"); 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() public view virtual returns (string memory) { return ''; } /** * @dev Returns tokenIDs owned by `_owner`. */ function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 totalOwned = _addressData[_owner].balance; require(totalOwned > 0, "balance 0"); uint256 supply = _collectionData.index; uint256[] memory tokenIDs = new uint256[](totalOwned); uint256 ownedIndex; address currentOwner; unchecked { for (uint256 i; i < supply; i++) { address currentAddress = _ownerships[i]; if (currentAddress != address(0)) { currentOwner = currentAddress; } if (currentOwner == _owner) { tokenIDs[ownedIndex++] = i; if (ownedIndex == totalOwned){ return tokenIDs; } } } } revert(); } function owner() public view returns (address) { return _contractOwner; } modifier onlyOwner() { require(owner() == _msgSender(), "Caller not owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { address oldOwner = _contractOwner; _contractOwner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev Returns `_owner`'s lock status and unlock timestamp in unix time, and personal lock cooldown in days. */ function getLockData(address _owner) public view returns (bool, uint256, uint256) { return (_addressData[_owner].locked, _addressData[_owner].lockedUnlockTimestamp, _addressData[_owner].lockedUnlockCooldown); } /** * @dev Returns the token collection information. */ function collectionInformation() public view returns (collectionData memory) { return _collectionData; } function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC721Metadata } } abstract contract ERC721LBurnable is ERC721L { function _exists(uint256 tokenId) public view override returns (bool) { if (tokenId < _collectionData.index && _ownerships[tokenId] != address(0x000000000000000000000000000000000000dEaD)){ unchecked { address currentOwner = _ownerships[tokenId]; if (currentOwner != address(0)) { return true; } while (true) { tokenId--; currentOwner = _ownerships[tokenId]; if (currentOwner == address(0x000000000000000000000000000000000000dEaD)) { return false; } if (currentOwner != address(0)) { return true; } } } } return false; } function ownerOf(uint256 tokenId) public view override returns (address) { unchecked { if (tokenId < _collectionData.index) { address ownership = _ownerships[tokenId]; if (ownership != address(0x000000000000000000000000000000000000dEaD)) { if (ownership != address(0)) { return ownership; } while (true) { tokenId--; ownership = _ownerships[tokenId]; if (ownership != address(0)) { if (ownership == address(0x000000000000000000000000000000000000dEaD)) { revert ("Null Owner"); } return ownership; } } } } } revert (); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function burn(uint256 tokenId) public { address prevOwner = ownerOf(tokenId); require(isUnlocked(prevOwner), "ERC721L: Tokens Locked"); require((_msgSender() == prevOwner || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwner, _msgSender())), "ERC721L: Not Approved"); delete _tokenApprovals[tokenId]; unchecked { _addressData[prevOwner].balance -= 1; _ownerships[tokenId] = address(0x000000000000000000000000000000000000dEaD); _collectionData.burned++; uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = prevOwner; } } emit Transfer(prevOwner, address(0x000000000000000000000000000000000000dEaD), tokenId); } /** * @dev Destroys `tokenIDs`. * The approval is cleared when each token is burned. * * Requirements: * * - `tokenIDs` must exist. * - caller must be Owner or Approved for token usage. * * Emits a {Transfer} event. */ function batchBurn(uint256 startID, uint256 quantity) public { address currentOwner = ownerOf(startID); require(isUnlocked(currentOwner), "ERC721L: Tokens Locked"); require(multiOwnerCheck(currentOwner, startID, quantity), "ERC721L: Not Batchable"); require(_msgSender() == currentOwner || isApprovedForAll(currentOwner, _msgSender()), "ERC721M: Not Approved"); unchecked { for (uint256 i; i < quantity; i++) { uint256 currentToken = startID + i; delete _tokenApprovals[currentToken]; if (i == 0){ _ownerships[currentToken] = address(0x000000000000000000000000000000000000dEaD); } else { delete _ownerships[currentToken]; } emit Transfer(currentOwner, address(0x000000000000000000000000000000000000dEaD), currentToken); } _addressData[currentOwner].balance -= uint64(quantity); _collectionData.burned += uint128(quantity); uint256 nextTokenId = startID + quantity; if (_ownerships[nextTokenId] == address(0) && nextTokenId < _collectionData.index) { _ownerships[nextTokenId] = currentOwner; } } } } contract INHIBITOR is ERC721LBurnable { address public royaltyAddress; uint256 public royaltySize = 750; uint256 public royaltyDenominator = 10000; mapping(uint256 => address) private _royaltyReceivers; uint256 maxSupply = 7777; string private _baseURI = "ipfs://QmaQ2FarHPpr5TbjQmv6knusDeNBXETzWxRGnWzLsTgn4G/"; uint256 public publicMaxMint = 5; uint256 public priceInhibitor = .02 ether; bool public publicActive; address public genesisAddress; constructor(address _genesisAddress) ERC721L("INHIBITOR", "INHIB") { genesisAddress = _genesisAddress; royaltyAddress = owner(); } modifier callerIsUser() { require(tx.origin == _msgSender() && _msgSender().code.length == 0, "Contract Caller"); _; } modifier isGenesisContract() { require(genesisAddress == _msgSender(), "Caller not Genesis Contract"); _; } function mintHelper(address _minter, uint256 _quantity) public isGenesisContract { unchecked { require(totalCreated() + _quantity <= maxSupply, "Insufficient supply"); } _mint(_minter, _quantity); } function publicMint(uint256 _quantity) public payable callerIsUser() { require(publicActive, "Public sale not active"); require(_quantity > 0 && _quantity <= publicMaxMint, "Invalid quantity"); unchecked { require(totalCreated() + _quantity <= maxSupply, "Insufficient supply remaining"); require(msg.value >= priceInhibitor * _quantity, "Insufficient payment"); } _mint(_msgSender(), _quantity); } function baseURI() public view override returns (string memory) { return _baseURI; } function setBaseURI(string calldata newBaseURI) external onlyOwner { _baseURI = newBaseURI; } function setPublicState(bool _state) external onlyOwner { publicActive = _state; } function setPublicMaxMint(uint256 _newLimit) external onlyOwner { publicMaxMint = _newLimit; } function setInhibitorPrice(uint256 _price) external onlyOwner { priceInhibitor = _price; } function setGenesisAddress(address _address) external onlyOwner { genesisAddress = _address; } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { uint256 amount = (_salePrice * royaltySize)/(royaltyDenominator); address royaltyReceiver = _royaltyReceivers[_tokenId] != address(0) ? _royaltyReceivers[_tokenId] : royaltyAddress; return (royaltyReceiver, amount); } function addRoyaltyReceiverForTokenId(address receiver, uint256 tokenId) public onlyOwner { _royaltyReceivers[tokenId] = receiver; } function withdraw() external onlyOwner { uint256 currentBalance = address(this).balance; (bool sent, ) = address(msg.sender).call{value: currentBalance}(''); require(sent, "Transfer Error"); } }
Locks `_owner`'s tokens from any form of transferring. Requirements: - The `caller` cannot have their tokens locked currently. Emits a {Locked} event./
function lock(uint256 _cooldown) public { require(!_addressData[_msgSender()].locked, "Tokens currently locked"); require(_cooldown > 0 && _cooldown < 31, "Invalid Cooldown"); unchecked { uint256 proposedCooldown = _cooldown * 1 days; require(block.timestamp + proposedCooldown > _addressData[_msgSender()].lockedUnlockTimestamp, "Proposed cooldown too small"); _addressData[_msgSender()].locked = true; _addressData[_msgSender()].lockedUnlockCooldown = uint64(proposedCooldown); } emit Locked(_msgSender(), _cooldown); }
303,786
// 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; } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../interface/RocketStorageInterface.sol"; /// @title Base settings / modifiers for each contract in Rocket Pool /// @author David Rugendyke abstract contract RocketBase { // Calculate using this as the base uint256 constant calcBase = 1 ether; // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained RocketStorageInterface rocketStorage = RocketStorageInterface(0); /*** Modifiers **********************************************************/ /** * @dev Throws if called by any sender that doesn't match a Rocket Pool network contract */ modifier onlyLatestNetworkContract() { require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract"); _; } /** * @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract */ modifier onlyLatestContract(string memory _contractName, address _contractAddress) { require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract"); _; } /** * @dev Throws if called by any sender that isn't a registered node */ modifier onlyRegisteredNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node"); _; } /** * @dev Throws if called by any sender that isn't a trusted node DAO member */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered minipool */ modifier onlyRegisteredMinipool(address _minipoolAddress) { require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool"); _; } /** * @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled) */ modifier onlyGuardian() { require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian"); _; } /*** Methods **********************************************************/ /// @dev Set the main Rocket Storage address constructor(RocketStorageInterface _rocketStorageAddress) { // Update the contract address rocketStorage = RocketStorageInterface(_rocketStorageAddress); } /// @dev Get the address of a network contract by name function getContractAddress(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Check it require(contractAddress != address(0x0), "Contract not found"); // Return return contractAddress; } /// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist) function getContractAddressUnsafe(string memory _contractName) internal view returns (address) { // Get the current contract address address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName))); // Return return contractAddress; } /// @dev Get the name of a network contract by address function getContractName(address _contractAddress) internal view returns (string memory) { // Get the contract name string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress))); // Check it require(bytes(contractName).length > 0, "Contract not found"); // Return return contractName; } /// @dev Get revert error message from a .call method function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /*** Rocket Storage Methods ****************************************/ // Note: Unused helpers have been removed to keep contract sizes down /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); } function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); } /// @dev Storage arithmetic methods function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); } function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../../../RocketBase.sol"; import "../../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsInterface.sol"; // Settings in RP which the DAO will have full control over // This settings contract enables storage using setting paths with namespaces, rather than explicit set methods abstract contract RocketDAONodeTrustedSettings is RocketBase, RocketDAONodeTrustedSettingsInterface { // The namespace for a particular group of settings bytes32 settingNameSpace; // Only allow updating from the DAO proposals contract modifier onlyDAONodeTrustedProposal() { // If this contract has been initialised, only allow access from the proposals contract if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAONodeTrustedProposals") == msg.sender, "Only DAO Node Trusted Proposals contract can update a setting"); _; } // Construct constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) { // Apply the setting namespace settingNameSpace = keccak256(abi.encodePacked("dao.trustednodes.setting.", _settingNameSpace)); } /*** Uints ****************/ // A general method to return any setting given the setting path is correct, only accepts uints function getSettingUint(string memory _settingPath) public view override returns (uint256) { return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath))); } // Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAONodeTrustedProposal { // Update setting now setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } /*** Bools ****************/ // A general method to return any setting given the setting path is correct, only accepts bools function getSettingBool(string memory _settingPath) public view override returns (bool) { return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath))); } // Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAONodeTrustedProposal { // Update setting now setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RocketDAONodeTrustedSettings.sol"; import "../../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsMinipoolInterface.sol"; import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsMinipoolInterface.sol"; // The Trusted Node DAO Minipool settings contract RocketDAONodeTrustedSettingsMinipool is RocketDAONodeTrustedSettings, RocketDAONodeTrustedSettingsMinipoolInterface { using SafeMath for uint; // Construct constructor(RocketStorageInterface _rocketStorageAddress) RocketDAONodeTrustedSettings(_rocketStorageAddress, "minipool") { // Set version version = 1; // If deployed during initial deployment, initialise now (otherwise must be called after upgrade) if (!_rocketStorageAddress.getDeployedStatus()){ initialise(); } } // Initialise function initialise() public { // Initialize settings on deployment require(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed"))), "Already initialised"); // Init settings setSettingUint("minipool.scrub.period", 12 hours); setSettingUint("minipool.scrub.quorum", 0.51 ether); setSettingBool("minipool.scrub.penalty.enabled", false); // Settings initialised setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true); } // Update a setting, overrides inherited setting method with extra checks for this contract function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAONodeTrustedProposal { // Some safety guards for certain settings if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) { if(keccak256(abi.encodePacked(_settingPath)) == keccak256(abi.encodePacked("minipool.scrub.period"))) { RocketDAOProtocolSettingsMinipoolInterface rocketDAOProtocolSettingsMinipool = RocketDAOProtocolSettingsMinipoolInterface(getContractAddress("rocketDAOProtocolSettingsMinipool")); require(_value <= (rocketDAOProtocolSettingsMinipool.getLaunchTimeout().sub(1 hours)), "Scrub period must be less than launch timeout"); } } // Update setting now setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value); } // Getters // How long minipools must wait before moving to staking status (can be scrubbed by ODAO before then) function getScrubPeriod() override external view returns (uint256) { return getSettingUint("minipool.scrub.period"); } // The required number of trusted nodes to vote to scrub a minipool function getScrubQuorum() override external view returns (uint256) { return getSettingUint("minipool.scrub.quorum"); } // True if scrubbing results in an RPL penalty for the node operator function getScrubPenaltyEnabled() override external view returns (bool) { return getSettingBool("minipool.scrub.penalty.enabled"); } } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketStorageInterface { // Deploy status function getDeployedStatus() external view returns (bool); // Guardian function getGuardian() external view returns(address); function setGuardian(address _newAddress) external; function confirmGuardian() external; // Getters function getAddress(bytes32 _key) external view returns (address); function getUint(bytes32 _key) external view returns (uint); function getString(bytes32 _key) external view returns (string memory); function getBytes(bytes32 _key) external view returns (bytes memory); function getBool(bytes32 _key) external view returns (bool); function getInt(bytes32 _key) external view returns (int); function getBytes32(bytes32 _key) external view returns (bytes32); // Setters function setAddress(bytes32 _key, address _value) external; function setUint(bytes32 _key, uint _value) external; function setString(bytes32 _key, string calldata _value) external; function setBytes(bytes32 _key, bytes calldata _value) external; function setBool(bytes32 _key, bool _value) external; function setInt(bytes32 _key, int _value) external; function setBytes32(bytes32 _key, bytes32 _value) external; // Deleters function deleteAddress(bytes32 _key) external; function deleteUint(bytes32 _key) external; function deleteString(bytes32 _key) external; function deleteBytes(bytes32 _key) external; function deleteBool(bytes32 _key) external; function deleteInt(bytes32 _key) external; function deleteBytes32(bytes32 _key) external; // Arithmetic function addUint(bytes32 _key, uint256 _amount) external; function subUint(bytes32 _key, uint256 _amount) external; // Protected storage function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address); function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address); function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external; function confirmWithdrawalAddress(address _nodeAddress) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedSettingsInterface { function getSettingUint(string memory _settingPath) external view returns (uint256); function setSettingUint(string memory _settingPath, uint256 _value) external; function getSettingBool(string memory _settingPath) external view returns (bool); function setSettingBool(string memory _settingPath, bool _value) external; } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only interface RocketDAONodeTrustedSettingsMinipoolInterface { function getScrubPeriod() external view returns(uint256); function getScrubQuorum() external view returns(uint256); function getScrubPenaltyEnabled() external view returns(bool); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only import "../../../../types/MinipoolDeposit.sol"; interface RocketDAOProtocolSettingsMinipoolInterface { function getLaunchBalance() external view returns (uint256); function getDepositNodeAmount(MinipoolDeposit _depositType) external view returns (uint256); function getFullDepositNodeAmount() external view returns (uint256); function getHalfDepositNodeAmount() external view returns (uint256); function getEmptyDepositNodeAmount() external view returns (uint256); function getDepositUserAmount(MinipoolDeposit _depositType) external view returns (uint256); function getFullDepositUserAmount() external view returns (uint256); function getHalfDepositUserAmount() external view returns (uint256); function getEmptyDepositUserAmount() external view returns (uint256); function getSubmitWithdrawableEnabled() external view returns (bool); function getLaunchTimeout() external view returns (uint256); function getMaximumCount() external view returns (uint256); } /** * . * / \ * |.'.| * |'.'| * ,'| |`. * |,-'-|-'-.| * __|_| | _ _ _____ _ * | ___ \| | | | | | ___ \ | | * | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | | * | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| | * | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | | * \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_| * +---------------------------------------------------+ * | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM | * +---------------------------------------------------+ * * Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to * be community-owned, decentralised, and trustless. * * For more information about Rocket Pool, visit https://rocketpool.net * * Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty * */ pragma solidity 0.7.6; // SPDX-License-Identifier: GPL-3.0-only // Represents the type of deposits required by a minipool enum MinipoolDeposit { None, // Marks an invalid deposit type Full, // The minipool requires 32 ETH from the node operator, 16 ETH of which will be refinanced from user deposits Half, // The minipool required 16 ETH from the node operator to be matched with 16 ETH from user deposits Empty // The minipool requires 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only) }
Update a setting, overrides inherited setting method with extra checks for this contract Some safety guards for certain settings
function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAONodeTrustedProposal { if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) { if(keccak256(abi.encodePacked(_settingPath)) == keccak256(abi.encodePacked("minipool.scrub.period"))) { RocketDAOProtocolSettingsMinipoolInterface rocketDAOProtocolSettingsMinipool = RocketDAOProtocolSettingsMinipoolInterface(getContractAddress("rocketDAOProtocolSettingsMinipool")); require(_value <= (rocketDAOProtocolSettingsMinipool.getLaunchTimeout().sub(1 hours)), "Scrub period must be less than launch timeout"); } } }
12,028,781