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.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../common/CalledByVm.sol"; import "../common/FixidityLib.sol"; import "../common/Freezable.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; import "../common/UsingPrecompiles.sol"; /** * @title Contract for calculating epoch rewards. */ contract EpochRewards is Ownable, Initializable, UsingPrecompiles, UsingRegistry, Freezable, CalledByVm { using FixidityLib for FixidityLib.Fraction; using SafeMath for uint256; uint256 constant GENESIS_GOLD_SUPPLY = 600000000 ether; // 600 million Gold uint256 constant GOLD_SUPPLY_CAP = 1000000000 ether; // 1 billion Gold uint256 constant YEARS_LINEAR = 15; uint256 constant SECONDS_LINEAR = YEARS_LINEAR * 365 * 1 days; // This struct governs how the rewards multiplier should deviate from 1.0 based on the ratio of // supply remaining to target supply remaining. struct RewardsMultiplierAdjustmentFactors { FixidityLib.Fraction underspend; FixidityLib.Fraction overspend; } // This struct governs the multiplier on the target rewards to give out in a given epoch due to // potential deviations in the actual Gold total supply from the target total supply. // In the case where the actual exceeds the target (i.e. the protocol has "overspent" with // respect to epoch rewards and payments) the rewards multiplier will be less than one. // In the case where the actual is less than the target (i.e. the protocol has "underspent" with // respect to epoch rewards and payments) the rewards multiplier will be greater than one. struct RewardsMultiplierParameters { RewardsMultiplierAdjustmentFactors adjustmentFactors; // The maximum rewards multiplier. FixidityLib.Fraction max; } // This struct governs the target yield awarded to voters in validator elections. struct TargetVotingYieldParameters { // The target yield awarded to users voting in validator elections. FixidityLib.Fraction target; // Governs the adjustment of the target yield based on the deviation of the percentage of // Gold voting in validator elections from the `targetVotingGoldFraction`. FixidityLib.Fraction adjustmentFactor; // The maximum target yield awarded to users voting in validator elections. FixidityLib.Fraction max; } uint256 public startTime = 0; RewardsMultiplierParameters private rewardsMultiplierParams; TargetVotingYieldParameters private targetVotingYieldParams; FixidityLib.Fraction private targetVotingGoldFraction; FixidityLib.Fraction private communityRewardFraction; FixidityLib.Fraction private carbonOffsettingFraction; address public carbonOffsettingPartner; uint256 public targetValidatorEpochPayment; event TargetVotingGoldFractionSet(uint256 fraction); event CommunityRewardFractionSet(uint256 fraction); event CarbonOffsettingFundSet(address indexed partner, uint256 fraction); event TargetValidatorEpochPaymentSet(uint256 payment); event TargetVotingYieldParametersSet(uint256 max, uint256 adjustmentFactor); event TargetVotingYieldSet(uint256 target); event RewardsMultiplierParametersSet( uint256 max, uint256 underspendAdjustmentFactor, uint256 overspendAdjustmentFactor ); event TargetVotingYieldUpdated(uint256 fraction); /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry contract. * @param targetVotingYieldInitial The initial relative target block reward for voters. * @param targetVotingYieldMax The max relative target block reward for voters. * @param targetVotingYieldAdjustmentFactor The target block reward adjustment factor for voters. * @param rewardsMultiplierMax The max multiplier on target epoch rewards. * @param rewardsMultiplierUnderspendAdjustmentFactor Adjusts the multiplier on target epoch * rewards when the protocol is running behind the target Gold supply. * @param rewardsMultiplierOverspendAdjustmentFactor Adjusts the multiplier on target epoch * rewards when the protocol is running ahead of the target Gold supply. * @param _targetVotingGoldFraction The percentage of floating Gold voting to target. * @param _targetValidatorEpochPayment The target validator epoch payment. * @param _communityRewardFraction The percentage of rewards that go the community funds. * @param _carbonOffsettingPartner The address of the carbon offsetting partner. * @param _carbonOffsettingFraction The percentage of rewards going to carbon offsetting partner. * @dev Should be called only once. */ function initialize( address registryAddress, uint256 targetVotingYieldInitial, uint256 targetVotingYieldMax, uint256 targetVotingYieldAdjustmentFactor, uint256 rewardsMultiplierMax, uint256 rewardsMultiplierUnderspendAdjustmentFactor, uint256 rewardsMultiplierOverspendAdjustmentFactor, uint256 _targetVotingGoldFraction, uint256 _targetValidatorEpochPayment, uint256 _communityRewardFraction, address _carbonOffsettingPartner, uint256 _carbonOffsettingFraction ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setTargetVotingYieldParameters(targetVotingYieldMax, targetVotingYieldAdjustmentFactor); setRewardsMultiplierParameters( rewardsMultiplierMax, rewardsMultiplierUnderspendAdjustmentFactor, rewardsMultiplierOverspendAdjustmentFactor ); setTargetVotingGoldFraction(_targetVotingGoldFraction); setTargetValidatorEpochPayment(_targetValidatorEpochPayment); setCommunityRewardFraction(_communityRewardFraction); setCarbonOffsettingFund(_carbonOffsettingPartner, _carbonOffsettingFraction); setTargetVotingYield(targetVotingYieldInitial); startTime = now; } /** * @notice Returns the target voting yield parameters. * @return The target, max, and adjustment factor for target voting yield. */ function getTargetVotingYieldParameters() external view returns (uint256, uint256, uint256) { TargetVotingYieldParameters storage params = targetVotingYieldParams; return (params.target.unwrap(), params.max.unwrap(), params.adjustmentFactor.unwrap()); } /** * @notice Returns the rewards multiplier parameters. * @return The max multiplier and under/over spend adjustment factors. */ function getRewardsMultiplierParameters() external view returns (uint256, uint256, uint256) { RewardsMultiplierParameters storage params = rewardsMultiplierParams; return ( params.max.unwrap(), params.adjustmentFactors.underspend.unwrap(), params.adjustmentFactors.overspend.unwrap() ); } /** * @notice Sets the community reward percentage * @param value The percentage of the total reward to be sent to the community funds. * @return True upon success. */ function setCommunityRewardFraction(uint256 value) public onlyOwner returns (bool) { require(value != communityRewardFraction.unwrap() && value < FixidityLib.fixed1().unwrap()); communityRewardFraction = FixidityLib.wrap(value); emit CommunityRewardFractionSet(value); return true; } /** * @notice Returns the community reward fraction. * @return The percentage of total reward which goes to the community funds. */ function getCommunityRewardFraction() external view returns (uint256) { return communityRewardFraction.unwrap(); } /** * @notice Sets the carbon offsetting fund. * @param partner The address of the carbon offsetting partner. * @param value The percentage of the total reward to be sent to the carbon offsetting partner. * @return True upon success. */ function setCarbonOffsettingFund(address partner, uint256 value) public onlyOwner returns (bool) { require(partner != carbonOffsettingPartner || value != carbonOffsettingFraction.unwrap()); require(value < FixidityLib.fixed1().unwrap()); carbonOffsettingPartner = partner; carbonOffsettingFraction = FixidityLib.wrap(value); emit CarbonOffsettingFundSet(partner, value); return true; } /** * @notice Returns the carbon offsetting partner reward fraction. * @return The percentage of total reward which goes to the carbon offsetting partner. */ function getCarbonOffsettingFraction() external view returns (uint256) { return carbonOffsettingFraction.unwrap(); } /** * @notice Sets the target voting Gold fraction. * @param value The percentage of floating Gold voting to target. * @return True upon success. */ function setTargetVotingGoldFraction(uint256 value) public onlyOwner returns (bool) { require(value != targetVotingGoldFraction.unwrap(), "Target voting gold fraction unchanged"); require( value < FixidityLib.fixed1().unwrap(), "Target voting gold fraction cannot be larger than 1" ); targetVotingGoldFraction = FixidityLib.wrap(value); emit TargetVotingGoldFractionSet(value); return true; } /** * @notice Returns the target voting Gold fraction. * @return The percentage of floating Gold voting to target. */ function getTargetVotingGoldFraction() external view returns (uint256) { return targetVotingGoldFraction.unwrap(); } /** * @notice Sets the target per-epoch payment in Celo Dollars for validators. * @param value The value in Celo Dollars. * @return True upon success. */ function setTargetValidatorEpochPayment(uint256 value) public onlyOwner returns (bool) { require(value != targetValidatorEpochPayment, "Target validator epoch payment unchanged"); targetValidatorEpochPayment = value; emit TargetValidatorEpochPaymentSet(value); return true; } /** * @notice Sets the rewards multiplier parameters. * @param max The max multiplier on target epoch rewards. * @param underspendAdjustmentFactor Adjusts the multiplier on target epoch rewards when the * protocol is running behind the target Gold supply. * @param overspendAdjustmentFactor Adjusts the multiplier on target epoch rewards when the * protocol is running ahead of the target Gold supply. * @return True upon success. */ function setRewardsMultiplierParameters( uint256 max, uint256 underspendAdjustmentFactor, uint256 overspendAdjustmentFactor ) public onlyOwner returns (bool) { require( max != rewardsMultiplierParams.max.unwrap() || overspendAdjustmentFactor != rewardsMultiplierParams.adjustmentFactors.overspend.unwrap() || underspendAdjustmentFactor != rewardsMultiplierParams.adjustmentFactors.underspend.unwrap(), "Bad rewards multiplier parameters" ); rewardsMultiplierParams = RewardsMultiplierParameters( RewardsMultiplierAdjustmentFactors( FixidityLib.wrap(underspendAdjustmentFactor), FixidityLib.wrap(overspendAdjustmentFactor) ), FixidityLib.wrap(max) ); emit RewardsMultiplierParametersSet(max, underspendAdjustmentFactor, overspendAdjustmentFactor); return true; } /** * @notice Sets the target voting yield parameters. * @param max The max relative target block reward for voters. * @param adjustmentFactor The target block reward adjustment factor for voters. * @return True upon success. */ function setTargetVotingYieldParameters(uint256 max, uint256 adjustmentFactor) public onlyOwner returns (bool) { require( max != targetVotingYieldParams.max.unwrap() || adjustmentFactor != targetVotingYieldParams.adjustmentFactor.unwrap(), "Bad target voting yield parameters" ); targetVotingYieldParams.max = FixidityLib.wrap(max); targetVotingYieldParams.adjustmentFactor = FixidityLib.wrap(adjustmentFactor); require( targetVotingYieldParams.max.lt(FixidityLib.fixed1()), "Max target voting yield must be lower than 100%" ); emit TargetVotingYieldParametersSet(max, adjustmentFactor); return true; } /** * @notice Sets the target voting yield. Uses fixed point arithmetic * for protection against overflow. * @param targetVotingYield The relative target block reward for voters. * @return True upon success. */ function setTargetVotingYield(uint256 targetVotingYield) public onlyOwner returns (bool) { FixidityLib.Fraction memory target = FixidityLib.wrap(targetVotingYield); require( target.lte(targetVotingYieldParams.max), "Target voting yield must be less than or equal to max" ); targetVotingYieldParams.target = target; emit TargetVotingYieldSet(targetVotingYield); return true; } /** * @notice Returns the target Gold supply according to the epoch rewards target schedule. * @return The target Gold supply according to the epoch rewards target schedule. */ function getTargetGoldTotalSupply() public view returns (uint256) { uint256 timeSinceInitialization = now.sub(startTime); if (timeSinceInitialization < SECONDS_LINEAR) { // Pay out half of all block rewards linearly. uint256 linearRewards = GOLD_SUPPLY_CAP.sub(GENESIS_GOLD_SUPPLY).div(2); uint256 targetRewards = linearRewards.mul(timeSinceInitialization).div(SECONDS_LINEAR); return targetRewards.add(GENESIS_GOLD_SUPPLY); } else { // TODO(asa): Implement block reward calculation for years 15-30. require(false, "Implement block reward calculation for years 15-30"); return 0; } } /** * @notice Returns the rewards multiplier based on the current and target Gold supplies. * @param targetGoldSupplyIncrease The target increase in current Gold supply. * @return The rewards multiplier based on the current and target Gold supplies. */ function _getRewardsMultiplier(uint256 targetGoldSupplyIncrease) internal view returns (FixidityLib.Fraction memory) { uint256 targetSupply = getTargetGoldTotalSupply(); uint256 totalSupply = getGoldToken().totalSupply(); uint256 remainingSupply = GOLD_SUPPLY_CAP.sub(totalSupply.add(targetGoldSupplyIncrease)); uint256 targetRemainingSupply = GOLD_SUPPLY_CAP.sub(targetSupply); FixidityLib.Fraction memory remainingToTargetRatio = FixidityLib .newFixed(remainingSupply) .divide(FixidityLib.newFixed(targetRemainingSupply)); if (remainingToTargetRatio.gt(FixidityLib.fixed1())) { FixidityLib.Fraction memory delta = remainingToTargetRatio .subtract(FixidityLib.fixed1()) .multiply(rewardsMultiplierParams.adjustmentFactors.underspend); FixidityLib.Fraction memory multiplier = FixidityLib.fixed1().add(delta); if (multiplier.lt(rewardsMultiplierParams.max)) { return multiplier; } else { return rewardsMultiplierParams.max; } } else if (remainingToTargetRatio.lt(FixidityLib.fixed1())) { FixidityLib.Fraction memory delta = FixidityLib .fixed1() .subtract(remainingToTargetRatio) .multiply(rewardsMultiplierParams.adjustmentFactors.overspend); if (delta.lt(FixidityLib.fixed1())) { return FixidityLib.fixed1().subtract(delta); } else { return FixidityLib.wrap(0); } } else { return FixidityLib.fixed1(); } } /** * @notice Returns the total target epoch rewards for voters. * @return the total target epoch rewards for voters. */ function getTargetVoterRewards() public view returns (uint256) { return FixidityLib .newFixed(getElection().getActiveVotes()) .multiply(targetVotingYieldParams.target) .fromFixed(); } /** * @notice Returns the total target epoch payments to validators, converted to Gold. * @return The total target epoch payments to validators, converted to Gold. */ function getTargetTotalEpochPaymentsInGold() public view returns (uint256) { address stableTokenAddress = registry.getAddressForOrDie(STABLE_TOKEN_REGISTRY_ID); (uint256 numerator, uint256 denominator) = getSortedOracles().medianRate(stableTokenAddress); return numberValidatorsInCurrentSet().mul(targetValidatorEpochPayment).mul(denominator).div( numerator ); } /** * @notice Returns the target gold supply increase used in calculating the rewards multiplier. * @return The target increase in gold w/out the rewards multiplier. */ function _getTargetGoldSupplyIncrease() internal view returns (uint256) { uint256 targetEpochRewards = getTargetVoterRewards(); uint256 targetTotalEpochPaymentsInGold = getTargetTotalEpochPaymentsInGold(); uint256 targetGoldSupplyIncrease = targetEpochRewards.add(targetTotalEpochPaymentsInGold); // increase /= (1 - fraction) st the final community reward is fraction * increase targetGoldSupplyIncrease = FixidityLib .newFixed(targetGoldSupplyIncrease) .divide( FixidityLib.newFixed(1).subtract(communityRewardFraction).subtract(carbonOffsettingFraction) ) .fromFixed(); return targetGoldSupplyIncrease; } /** * @notice Returns the rewards multiplier based on the current and target Gold supplies. * @return The rewards multiplier based on the current and target Gold supplies. */ function getRewardsMultiplier() external view returns (uint256) { return _getRewardsMultiplier(_getTargetGoldSupplyIncrease()).unwrap(); } /** * @notice Returns the fraction of floating Gold being used for voting in validator elections. * @return The fraction of floating Gold being used for voting in validator elections. */ function getVotingGoldFraction() public view returns (uint256) { uint256 liquidGold = getGoldToken().totalSupply().sub(getReserve().getReserveGoldBalance()); uint256 votingGold = getElection().getTotalVotes(); return FixidityLib.newFixed(votingGold).divide(FixidityLib.newFixed(liquidGold)).unwrap(); } /** * @notice Updates the target voting yield based on the difference between the target and current * voting Gold fraction. */ function _updateTargetVotingYield() internal onlyWhenNotFrozen { FixidityLib.Fraction memory votingGoldFraction = FixidityLib.wrap(getVotingGoldFraction()); if (votingGoldFraction.gt(targetVotingGoldFraction)) { FixidityLib.Fraction memory votingGoldFractionDelta = votingGoldFraction.subtract( targetVotingGoldFraction ); FixidityLib.Fraction memory targetVotingYieldDelta = votingGoldFractionDelta.multiply( targetVotingYieldParams.adjustmentFactor ); if (targetVotingYieldDelta.gte(targetVotingYieldParams.target)) { targetVotingYieldParams.target = FixidityLib.newFixed(0); } else { targetVotingYieldParams.target = targetVotingYieldParams.target.subtract( targetVotingYieldDelta ); } } else if (votingGoldFraction.lt(targetVotingGoldFraction)) { FixidityLib.Fraction memory votingGoldFractionDelta = targetVotingGoldFraction.subtract( votingGoldFraction ); FixidityLib.Fraction memory targetVotingYieldDelta = votingGoldFractionDelta.multiply( targetVotingYieldParams.adjustmentFactor ); targetVotingYieldParams.target = targetVotingYieldParams.target.add(targetVotingYieldDelta); if (targetVotingYieldParams.target.gt(targetVotingYieldParams.max)) { targetVotingYieldParams.target = targetVotingYieldParams.max; } } emit TargetVotingYieldUpdated(targetVotingYieldParams.target.unwrap()); } /** * @notice Updates the target voting yield based on the difference between the target and current * voting Gold fraction. * @dev Only called directly by the protocol. */ function updateTargetVotingYield() external onlyVm onlyWhenNotFrozen { _updateTargetVotingYield(); } /** * @notice Determines if the reserve is low enough to demand a diversion from * the community reward. Targets initial critical ratio of 2 with a linear * decline until 25 years have passed where the critical ratio will be 1. */ function isReserveLow() external view returns (bool) { // critical reserve ratio = 2 - time in second / 25 years FixidityLib.Fraction memory timeSinceInitialization = FixidityLib.newFixed(now.sub(startTime)); FixidityLib.Fraction memory m = FixidityLib.newFixed(25 * 365 * 1 days); FixidityLib.Fraction memory b = FixidityLib.newFixed(2); FixidityLib.Fraction memory criticalRatio; // Don't let the critical reserve ratio go under 1 after 25 years. if (timeSinceInitialization.gte(m)) { criticalRatio = FixidityLib.fixed1(); } else { criticalRatio = b.subtract(timeSinceInitialization.divide(m)); } FixidityLib.Fraction memory ratio = FixidityLib.wrap(getReserve().getReserveRatio()); return ratio.lte(criticalRatio); } /** * @notice Calculates the per validator epoch payment and the total rewards to voters. * @return The per validator epoch reward, the total rewards to voters, the total community * reward, and the total carbon offsetting partner reward. */ function calculateTargetEpochRewards() external view onlyWhenNotFrozen returns (uint256, uint256, uint256, uint256) { uint256 targetVoterReward = getTargetVoterRewards(); uint256 targetGoldSupplyIncrease = _getTargetGoldSupplyIncrease(); FixidityLib.Fraction memory rewardsMultiplier = _getRewardsMultiplier(targetGoldSupplyIncrease); return ( FixidityLib.newFixed(targetValidatorEpochPayment).multiply(rewardsMultiplier).fromFixed(), FixidityLib.newFixed(targetVoterReward).multiply(rewardsMultiplier).fromFixed(), FixidityLib .newFixed(targetGoldSupplyIncrease) .multiply(communityRewardFraction) .multiply(rewardsMultiplier) .fromFixed(), FixidityLib .newFixed(targetGoldSupplyIncrease) .multiply(carbonOffsettingFraction) .multiply(rewardsMultiplier) .fromFixed() ); } }
Returns the rewards multiplier based on the current and target Gold supplies. return The rewards multiplier based on the current and target Gold supplies./
function getRewardsMultiplier() external view returns (uint256) { return _getRewardsMultiplier(_getTargetGoldSupplyIncrease()).unwrap(); }
12,996,414
./partial_match/1/0xb2a47999b3117c7dD628920ED8e77eBDfB948B68/sources/contracts/NounsDescriptorV2.sol
Update a single color palette. This function can be used to add a new color palette or update an existing palette. This function does not check for data length validity (len <= 768, len % 3 == 0). paletteIndex the identifier of this palette pointer the address of the contract holding the palette bytes. every 3 bytes represent an RGB color. max length: 256 3 = 768. This function can only be called by the owner when not locked./
function setPalettePointer(uint8 paletteIndex, address pointer) external override onlyOwner whenPartsNotLocked { art.setPalettePointer(paletteIndex, pointer); }
4,114,984
// Voting.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/access/Ownable.sol"; contract Voting is Ownable { /* Can be improved with some assert to check the count of vote after and before votes etc... */ struct Voter { bool isRegistered; bool hasVoted; uint256 votedProposalId; } struct Proposal { string description; uint256 voteCount; } enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } event VoterRegistered(address voterAddress); event ProposalsRegistrationStarted(); event ProposalsRegistrationEnded(); event ProposalRegistered(uint256 proposalId); event VotingSessionStarted(); event VotingSessionEnded(); event Voted(address voter, uint256 proposalId); event VotesTallied(); event WorkflowStatusChange( WorkflowStatus previousStatus, WorkflowStatus newStatus ); uint256 proposalId = 0; uint256 winningProposalId; // Declare workflow variable of type WorkflowStatus (which is enum) WorkflowStatus public workflow = WorkflowStatus.RegisteringVoters; //default = RegisteringVoters // Mapping mapping(address => Voter) whitelist; //map a voter to his address mapping(uint256 => Proposal) proposals; //map a proposal to his id // 1) Owner register the whitelist function registerVoter(address _address) public onlyOwner { require( !whitelist[_address].isRegistered, "this voter is already registered" ); Voter memory newVoter; newVoter.isRegistered = true; whitelist[_address] = newVoter; emit VoterRegistered(_address); } // 2) Owner makes register session begin function startProposalsRegistration() public onlyOwner { require( workflow == WorkflowStatus.RegisteringVoters, "Must be in the RegisteringVoters to start ProposalsRegistration" ); workflow = WorkflowStatus.ProposalsRegistrationStarted; emit ProposalsRegistrationStarted(); emit WorkflowStatusChange( WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted ); } // 3) Whitelisted voters can register proposals function saveProposal(string memory _description) public { require( workflow == WorkflowStatus.ProposalsRegistrationStarted, "Saving a proposal must be during the Registration workflow" ); require( whitelist[msg.sender].isRegistered, "A voter must be registered to save a proposal" ); Proposal memory newProposal; newProposal.description = _description; proposals[proposalId] = newProposal; emit ProposalRegistered(proposalId); proposalId++; } // 4) Owner makes register session end function endProposalsRegistration() public onlyOwner { require( workflow == WorkflowStatus.ProposalsRegistrationStarted, "ProposalsRegistration must have been started to end it" ); workflow = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded ); } // 5) Owner makes voting session begin function startVotingSession() public onlyOwner { require( workflow == WorkflowStatus.ProposalsRegistrationEnded, "ProposalsRegistration must end before to start the VotingSession" ); workflow = WorkflowStatus.VotingSessionStarted; emit VotingSessionStarted(); emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted ); } // 6) Whitelisted voters can vote for proposals function voteForProposal(uint256 _proposalId) public { require( workflow == WorkflowStatus.VotingSessionStarted, "Voting for proposal must be during the Voting session" ); require( whitelist[msg.sender].isRegistered, "A voter must be registered to save a proposal" ); require( _proposalId <= proposalId, "Your choice of proposal is too high, there are less proposals" ); require(!whitelist[msg.sender].hasVoted, "Voter can only vote once"); whitelist[msg.sender].hasVoted = true; whitelist[msg.sender].votedProposalId = _proposalId; proposals[_proposalId].voteCount++; emit Voted(msg.sender, _proposalId); } // 7) Owner makes voting session end function endVotingSession() public onlyOwner { require( workflow == WorkflowStatus.VotingSessionStarted, "VotingSession must have been started to end it" ); workflow = WorkflowStatus.VotingSessionEnded; emit VotingSessionEnded(); emit WorkflowStatusChange( WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded ); } // 8) Owner count the votes function tallyVotes() public onlyOwner { require( workflow == WorkflowStatus.VotingSessionEnded, "VotingSession must have ended before VotesTallied" ); workflow = WorkflowStatus.VotesTallied; emit VotesTallied(); emit WorkflowStatusChange( WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied ); // tally the vote winningProposalId = 0; // init winningProposalId for (uint256 i = 0; i < proposalId; i++) { if ( proposals[i].voteCount > proposals[winningProposalId].voteCount ) { winningProposalId = i; } } } // 9) Everyone can see the restults function getWinningProposal() public view returns (uint256) { return winningProposalId; } // non mandatory for Defi but useful for my test function getNumOfProposals() public view onlyOwner returns (uint256) { return proposalId; } }
4) Owner makes register session end
function endProposalsRegistration() public onlyOwner { require( workflow == WorkflowStatus.ProposalsRegistrationStarted, "ProposalsRegistration must have been started to end it" ); workflow = WorkflowStatus.ProposalsRegistrationEnded; emit ProposalsRegistrationEnded(); emit WorkflowStatusChange( WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded ); }
5,476,224
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.0; interface IERC20 { 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 success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); } interface IWETH { 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 success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function deposit() external payable; function withdraw(uint wad) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface Gastoken { function free(uint256 value) external returns (bool success); function freeUpTo(uint256 value) external returns (uint256 freed); function freeFrom(address from, uint256 value) external returns (bool success); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); function mint(uint256 value) external; } contract Sandwich { address owner = address(0x8C14877fe86b23FCF669350d056cDc3F2fC27029); IWETH weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); constructor() {} receive() external payable {} fallback() external payable {} modifier onlyOwner { require(msg.sender == owner); _; } function mintGastoken(address gasTokenAddress, uint _amount) external { Gastoken(gasTokenAddress).mint(_amount); } function withdrawERC20(address _token, uint _amount) external onlyOwner { IERC20(_token).transfer(msg.sender, _amount); } function approveMax(address router, address token) external onlyOwner { IERC20(token).approve(router, type(uint).max); } function _swapExactTokensToTokens( address gasTokenAddress, uint amountToFree, address inputToken, uint256 inputAmount, uint256 minOutAmount, address recipient, // IUniswapV2Pair[] calldata pairs, IUniswapV2Pair p, // bool[] calldata whichToken bool whichToken ) external onlyOwner { require(Gastoken(gasTokenAddress).free(amountToFree)); // Last trade, check for slippage here if (whichToken) { // Check what token are we buying, 0 or 1 ? // 1 (uint256 reserveIn, uint256 reserveOut,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded // require(inputAmount >= minOutAmount, "JRouter: not enough out tokens"); // Checking output amount p.swap(0, inputAmount, recipient, ""); // Swapping } else { // 0 (uint256 reserveOut, uint256 reserveIn,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded require(inputAmount >= minOutAmount, "JRouter: not enough out tokens"); // Checking output amount p.swap(inputAmount, 0, recipient, ""); // Swapping } } function _swapExactTokensToWETHAndBribe( address gasTokenAddress, uint amountToFree, address inputToken, uint256 minOutAmount, address recipient, IUniswapV2Pair p, bool whichToken, uint bribeAmount, uint bribePercentage ) external onlyOwner { uint startBalance = weth.balanceOf(address(this)); require(Gastoken(gasTokenAddress).free(amountToFree)); // Last trade, check for slippage here uint inputAmount = IERC20(inputToken).balanceOf(address(this)); if (whichToken) { // Check what token are we buying, 0 or 1 ? // 1 (uint256 reserveIn, uint256 reserveOut,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded // require(inputAmount >= minOutAmount, "JRouter: not enough out tokens"); // Checking output amount p.swap(0, inputAmount, recipient, ""); // Swapping } else { // 0 (uint256 reserveOut, uint256 reserveIn,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); // Breaks on Tether // IERC20(inputToken).transfer(address(p), inputAmount); inputAmount = inputAmount * 997; // Calculate after fee inputAmount = (inputAmount * reserveOut)/(reserveIn * 1000 + inputAmount); // Calculate outputNeeded // require(inputAmount >= minOutAmount, "JRouter: not enough out tokens"); // Checking output amount p.swap(inputAmount, 0, recipient, ""); // Swapping } uint balance = weth.balanceOf(address(this)); uint profit = balance - startBalance - minOutAmount; // This reverts if not profitable if (bribeAmount == 0) { bribeAmount = profit * bribePercentage / 100; } require(profit > bribeAmount, "Not enough money to pay bribe"); // however, we may not have enough for the bribe weth.withdraw(bribeAmount); block.coinbase.call{value: bribeAmount}(new bytes(0)); } }
IUniswapV2Pair[] calldata pairs, bool[] calldata whichToken Last trade, check for slippage here 1 require(inputAmount >= minOutAmount, "JRouter: not enough out tokens"); Checking output amount 0
function _swapExactTokensToTokens( address gasTokenAddress, uint amountToFree, address inputToken, uint256 inputAmount, uint256 minOutAmount, address recipient, IUniswapV2Pair p, bool whichToken ) external onlyOwner { require(Gastoken(gasTokenAddress).free(amountToFree)); (uint256 reserveIn, uint256 reserveOut,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); (uint256 reserveOut, uint256 reserveIn,) = p.getReserves(); require(IERC20(inputToken).transfer(address(p), inputAmount), "Transfer to pair failed"); }
5,717,628
./full_match/43113/0x2Ad8a117CAA5574f34CF28312E5715c153a3a147/sources/contracts/Governed.sol
Change the percentage of the fees applied Only callable by DAO. If the percentage is greater than 0, it must also have a fees owner. percentage The percentage of profits to be taken as fee
function setFeesPercentage(uint256 percentage) public { enforceCallerDAO(); if (percentage > 0) { require(feesOwner != address(0), "no fees owner"); } require(percentage < MAX_FEES_PERCENTAGE, "max percentage exceeded"); emit SetFeesPercentage(feesPercentage, percentage); feesPercentage = percentage; }
7,165,454
./partial_match/1/0xe3BE0054Da2F8da5002E8bdD8AA4c7fDf851E86D/sources/ERC721CreatorMaxMint.sol
Add to extension token tracking
function _preMintExtension(address to, uint256 tokenId) internal virtual override { uint256 length = totalSupplyExtension(msg.sender); _extensionTokens[msg.sender][length] = tokenId; _extensionTokensIndex[tokenId] = length; ++_extensionBalances[msg.sender]; _addTokenToOwnerEnumeration(to, tokenId, msg.sender); }
2,680,875
pragma solidity >=0.6.0 <0.7.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract YourCollectible is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; bool public paused = false; constructor(bytes32[] memory assetsForSale) public ERC721("ENSO NFT", "ENSO") { _setBaseURI("https://ipfs.io/ipfs/"); for (uint256 i = 0; i < assetsForSale.length; i++) { forSale[assetsForSale[i]] = true; } } //this marks an item in IPFS as "forsale" mapping(bytes32 => bool) public forSale; //this lets you look up a token by the uri (assuming there is only one of each uri for now) mapping(bytes32 => uint256) public uriToTokenId; function ownerMintItem(string memory tokenURI) public payable onlyOwner returns (uint256) { bytes32 uriHash = keccak256(abi.encodePacked(tokenURI)); //make sure they are only minting something that is marked "forsale" require(!paused, "sale is paused"); require(forSale[uriHash], "NOT FOR SALE"); console.log("Sender balanc tokens ww", msg.value); console.log("balance:", address(this).balance); console.log("#ofCollectibles:", balanceOf(msg.sender)); forSale[uriHash] = false; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); _setTokenURI(id, tokenURI); uriToTokenId[uriHash] = id; return id; } function mintItem(string memory tokenURI) public payable returns (uint256) { bytes32 uriHash = keccak256(abi.encodePacked(tokenURI)); //make sure they are only minting something that is marked "forsale" require(!paused, "sale is paused"); require(forSale[uriHash], "NOT FOR SALE"); require(msg.value >= 0.04 ether, "Value below price"); console.log("Sender balanc tokens ww", msg.value); console.log("balance:", address(this).balance); console.log("#ofCollectibles:", balanceOf(msg.sender)); forSale[uriHash] = false; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); _setTokenURI(id, tokenURI); uriToTokenId[uriHash] = id; return id; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } function pause(bool val) public onlyOwner { paused = val; } function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } }
make sure they are only minting something that is marked "forsale"
function mintItem(string memory tokenURI) public payable returns (uint256) { bytes32 uriHash = keccak256(abi.encodePacked(tokenURI)); require(!paused, "sale is paused"); require(forSale[uriHash], "NOT FOR SALE"); require(msg.value >= 0.04 ether, "Value below price"); console.log("Sender balanc tokens ww", msg.value); console.log("balance:", address(this).balance); console.log("#ofCollectibles:", balanceOf(msg.sender)); forSale[uriHash] = false; _tokenIds.increment(); uint256 id = _tokenIds.current(); _mint(msg.sender, id); _setTokenURI(id, tokenURI); uriToTokenId[uriHash] = id; return id; }
12,809,810
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, '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(uint(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 (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint 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(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint 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(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } interface IKeep3r { function isKeeper(address) external returns (bool); function worked(address keeper) external; } // sliding window oracle that uses observations collected over a window to provide moving price averages in the past // `windowSize` with a precision of `windowSize / granularity` contract UniswapV2Oracle { using FixedPoint for *; using SafeMath for uint; struct Observation { uint timestamp; uint price0Cumulative; uint price1Cumulative; } modifier upkeep() { require(KPR.isKeeper(msg.sender), "::isKeeper: keeper is not registered"); _; KPR.worked(msg.sender); } address public governance; address public pendingGovernance; /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } IKeep3r public constant KPR = IKeep3r(0xB63650C42d6fCcA02f5353A711cB85400dB6a8FE); address public immutable factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; // the desired amount of time over which the moving average should be computed, e.g. 24 hours uint public immutable windowSize = 14400; // the number of observations stored for each pair, i.e. how many price observations are stored for the window. // as granularity increases from 1, more frequent updates are needed, but moving averages become more precise. // averages are computed over intervals with sizes in the range: // [windowSize - (windowSize / granularity) * 2, windowSize] // e.g. if the window size is 24 hours, and the granularity is 24, the oracle will return the average price for // the period: // [now - [22 hours, 24 hours], now] uint8 public immutable granularity = 8; // this is redundant with granularity and windowSize, but stored for gas savings & informational purposes. uint public immutable periodSize = 1800; address[] internal _pairs; mapping(address => bool) internal _known; mapping(address => uint) public lastUpdated; function pairs() external view returns (address[] memory) { return _pairs; } // mapping from pair address to a list of price observations of that pair mapping(address => Observation[]) public pairObservations; constructor() public { governance = msg.sender; } // returns the index of the observation corresponding to the given timestamp function observationIndexOf(uint timestamp) public view returns (uint8 index) { uint epochPeriod = timestamp / periodSize; return uint8(epochPeriod % granularity); } // returns the observation from the oldest epoch (at the beginning of the window) relative to the current time function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); // no overflow issue. if observationIndex + 1 overflows, result is still zero. uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; } function updatePair(address pair) external returns (bool) { return _update(pair); } // update the cumulative price for the observation at the current timestamp. each observation is updated at most // once per epoch period. function update(address tokenA, address tokenB) external returns (bool) { address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); return _update(pair); } function add(address tokenA, address tokenB) external { require(msg.sender == governance, "UniswapV2Oracle::add: !gov"); address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB); require(!_known[pair], "known"); _known[pair] = true; _pairs.push(pair); } function work() public upkeep { bool worked = updateAll(); require(worked, "UniswapV2Oracle: no work"); } function updateAll() public returns (bool updated) { for (uint i = 0; i < _pairs.length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateFor(uint i, uint length) external returns (bool updated) { for (; i < length; i++) { if (_update(_pairs[i])) { updated = true; } } } function updateableList() external view returns (address[] memory list) { uint _index = 0; for (uint i = 0; i < _pairs.length; i++) { if (updateable(_pairs[i])) { list[_index++] = _pairs[i]; } } } function updateable(address pair) public view returns (bool) { return (block.timestamp - lastUpdated[pair]) > periodSize; } function updateable() external view returns (bool) { for (uint i = 0; i < _pairs.length; i++) { if (updateable(_pairs[i])) { return true; } } return false; } function updateableFor(uint i, uint length) external view returns (bool) { for (; i < length; i++) { if (updateable(_pairs[i])) { return true; } } return false; } function _update(address pair) internal returns (bool) { // populate the array with empty observations (first call only) for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } // get the observation for the current period uint8 observationIndex = observationIndexOf(block.timestamp); Observation storage observation = pairObservations[pair][observationIndex]; // we only want to commit updates once per period (i.e. windowSize / granularity) uint timeElapsed = block.timestamp - observation.timestamp; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; lastUpdated[pair] = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; return true; } return false; } // given the cumulative prices of the start and end of a period, and the length of the period, compute the average // price in terms of how much amount out is received for the amount in function computeAmountOut( uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed, uint amountIn ) private pure returns (uint amountOut) { // overflow is desired. FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112( uint224((priceCumulativeEnd - priceCumulativeStart) / timeElapsed) ); amountOut = priceAverage.mul(amountIn).decode144(); } // returns the amount out corresponding to the amount in for a given token using the moving average over the time // range [now - [windowSize, windowSize - periodSize * 2], now] // update must have been called for the bucket corresponding to timestamp `now - windowSize` function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) { address pair = UniswapV2Library.pairFor(factory, tokenIn, tokenOut); Observation storage firstObservation = getFirstObservationInWindow(pair); uint timeElapsed = block.timestamp - firstObservation.timestamp; require(timeElapsed <= windowSize, 'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION'); // should never happen. require(timeElapsed >= windowSize - periodSize * 2, 'SlidingWindowOracle: UNEXPECTED_TIME_ELAPSED'); (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); (address token0,) = UniswapV2Library.sortTokens(tokenIn, tokenOut); if (token0 == tokenIn) { return computeAmountOut(firstObservation.price0Cumulative, price0Cumulative, timeElapsed, amountIn); } else { return computeAmountOut(firstObservation.price1Cumulative, price1Cumulative, timeElapsed, amountIn); } } }
populate the array with empty observations (first call only)
function _update(address pair) internal returns (bool) { for (uint i = pairObservations[pair].length; i < granularity; i++) { pairObservations[pair].push(); } Observation storage observation = pairObservations[pair][observationIndex]; if (timeElapsed > periodSize) { (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair); observation.timestamp = block.timestamp; lastUpdated[pair] = block.timestamp; observation.price0Cumulative = price0Cumulative; observation.price1Cumulative = price1Cumulative; return true; } return false; }
6,681,012
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; /** * @dev ERC20 Contract Implementation */ contract ERC20 { mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; string public constant name = 'Doom Cult Society DAO'; string public constant symbol = 'CUL'; uint256 public constant decimals = 18; uint256 public constant CURRENCY_MULTIPLIER = 1000000000000000000; uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000; bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() {} function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256 result) { assembly { mstore(0x00, owner) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, spender) result := sload(keccak256(0x00, 0x40)) } } function approve(address spender, uint256 amount) public returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance; assembly { // currentAllowance = _allowances[sender][msg.sender] mstore(0x00, sender) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, caller()) let currentAllowanceSlot := keccak256(0x00, 0x40) currentAllowance := sload(currentAllowanceSlot) if gt(amount, currentAllowance) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 23) mstore(0x44, 'ERC20: amount>allowance') revert(0x00, 0x64) } } unchecked { _approve(sender, msg.sender, currentAllowance - amount); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal { assembly { mstore(0x00, sender) mstore(0x20, _balances.slot) let balancesSlot := keccak256(0x00, 0x40) let senderBalance := sload(balancesSlot) if or(or(iszero(sender), iszero(recipient)), gt(amount, senderBalance)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 32) mstore(0x44, 'ERC20: amount>balance or from==0') revert(0x00, 0x64) } sstore(balancesSlot, sub(senderBalance, amount)) mstore(0x00, recipient) balancesSlot := keccak256(0x00, 0x40) // skip overflow check as we only have 30,000 tokens sstore(balancesSlot, add(sload(balancesSlot), amount)) mstore(0x00, amount) log3(0x00, 0x20, TRANSFER_SIG, sender, recipient) } } function _approve( address owner, address spender, uint256 amount ) internal { assembly { if or(iszero(owner), iszero(spender)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 29) mstore(0x44, 'ERC20: approve from 0 address') revert(0x00, 0x64) } // _allowances[owner][spender] = amount mstore(0x00, owner) mstore(0x20, _allowances.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, spender) sstore(keccak256(0x00, 0x40), amount) // emit Approval(owner, spender, amount) mstore(0x00, amount) log3(0x00, 0x20, APPROVAL_SIG, owner, spender) } } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension but not the Enumerable extension */ contract ERC721 is IERC165, IERC721, IERC721Metadata { // Token name string public constant override name = 'Doom Cult Society'; // Token symbol string public constant override symbol = 'DCS'; uint256 internal constant ERROR_SIG = 0x08c379a000000000000000000000000000000000000000000000000000000000; // event signatures uint256 private constant APPROVAL_FOR_ALL_SIG = 0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31; bytes32 internal constant TRANSFER_SIG = 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef; bytes32 internal constant APPROVAL_SIG = 0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925; // Mapping from token ID to owner address mapping(uint256 => address) internal _owners; // Mapping owner address to token count mapping(address => uint256) internal _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId; } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256 res) { assembly { if iszero(owner) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 42) mstore(0x44, 'ERC721: balance query for the ze') mstore(0x64, 'ro address') revert(0x00, 0x84) } mstore(0x00, owner) mstore(0x20, _balances.slot) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address owner) { assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) // no need to mask address if we ensure everything written into _owners is an address owner := sload(keccak256(0x00, 0x40)) if iszero(owner) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 41) mstore(0x44, 'ERC721: owner query for nonexist') mstore(0x64, 'ent token') revert(0x00, 0x84) } } return owner; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256) public view virtual override returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); bool approvedForAll = isApprovedForAll(owner, msg.sender); /** * Failure cases * 1. to == owner (if ya wanna approve yourself go stare in a mirror!) * 2. !(msg.sender == owner OR approvedForAll == 1) */ assembly { if or(eq(to, owner), iszero(or(eq(caller(), owner), approvedForAll))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 19) mstore(0x44, 'ERC721: bad approve') revert(0x00, 0x64) } mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) sstore(keccak256(0x00, 0x40), to) log3(0x00, 0x20, APPROVAL_SIG, owner, to) } } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address res) { assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) if iszero(sload(keccak256(0x00, 0x40))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 19) mstore(0x44, 'ERC721: bad approve') revert(0x00, 0x64) } mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { assembly { if eq(operator, caller()) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 25) mstore(0x44, 'ERC721: approve to caller') revert(0x00, 0x64) } // _operatorApprovals[_msgSender()][operator] = approved mstore(0x00, caller()) mstore(0x20, _operatorApprovals.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, operator) sstore(keccak256(0x00, 0x40), approved) log4(0, 0, APPROVAL_FOR_ALL_SIG, caller(), operator, approved) } } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool res) { assembly { mstore(0x00, owner) mstore(0x20, _operatorApprovals.slot) mstore(0x20, keccak256(0x00, 0x40)) mstore(0x00, operator) res := sload(keccak256(0x00, 0x40)) } } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _isApprovedOrOwner(msg.sender, tokenId); _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 { _isApprovedOrOwner(msg.sender, tokenId); _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); bool isContract; assembly { isContract := gt(extcodesize(to), 0) } if (isContract) { _checkOnERC721ReceivedContract(from, to, tokenId, _data); } } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual { address owner; bool approvedForAll = isApprovedForAll(owner, spender); assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) owner := sload(keccak256(0x00, 0x40)) mstore(0x20, _tokenApprovals.slot) let approved := sload(keccak256(0x00, 0x40)) /** * Success Conditions * 1. spender = owner * 2. spender = approved * 3. approvedForAll = true * Also owner must NOT be 0 */ if or(iszero(or(or(eq(spender, owner), eq(approved, spender)), approvedForAll)), iszero(owner)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 44) mstore(0x44, 'ERC721: operator query for nonex') mstore(0x64, 'istent token') revert(0x00, 0x84) } } } /** * @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 { // address owner = ownerOf(tokenId); assembly { mstore(0x00, tokenId) mstore(0x20, _owners.slot) let owner := sload(keccak256(0x00, 0x40)) // Clear approvals from the previous owner mstore(0x00, tokenId) mstore(0x20, _tokenApprovals.slot) sstore(keccak256(0x00, 0x40), 0) log3(0x00, 0x20, APPROVAL_SIG, owner, 0) log3(0x00, 0x20, TRANSFER_SIG, from, to) // _owners[tokenId] = to mstore(0x20, _owners.slot) sstore(keccak256(0x00, 0x40), to) // _balances[from] -= 1 mstore(0x00, from) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) let fromBalance := sload(slot) sstore(slot, sub(fromBalance, 0x01)) // _balances[to] += 1 mstore(0x00, to) slot := keccak256(0x00, 0x40) sstore(slot, add(sload(slot), 1)) /** * Failure cases... * 1. owner != from * 2. to == 0 * 3. owner == 0 * 4. balances[from] == 0 */ if or(or(iszero(owner), iszero(fromBalance)), or(iszero(to), sub(owner, from))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 20) mstore(0x44, 'ERC721: bad transfer') revert(0x00, 0x64) } } } /** * @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 */ function _checkOnERC721ReceivedContract( address from, address to, uint256 tokenId, bytes memory _data ) internal { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { require( retval == IERC721Receiver(to).onERC721Received.selector, 'ERC721: transfer to non ERC721Receiver implementer' ); } catch (bytes memory reason) { if (reason.length == 0) { revert('ERC721: transfer to non ERC721Receiver implementer'); } else { assembly { revert(add(32, reason), mload(reason)) } } } } } /** * @dev DoomCultSocietyDAO * Decentralized Autonomous Doom! Doooooooooooooooooooooooom! * * The DAO controls cultist tokens: CUL * Cultist tokens are sacrificed in order to mint DoomCultSociety NFTs */ contract DoomCultSocietyDAO is ERC20 { uint256 internal constant WEEKS_UNTIL_OBLIVION = 52; uint256 internal constant SECONDS_PER_WEEK = 604800; uint256 public sleepTimer; // can wake up once block.timestamp > sleepTimer uint256 public doomCounter; // number of weeks until contract is destroyed uint256 public timestampUntilNextEpoch; // countdown timer can decrease once block.timestamp > timestampUntilNextEpoch // potential max cultists (incl. currency multiplier. This is 30,000 CUL) uint256 internal constant MAX_CULTISTS = 30000000000000000000000; // how many do we actually start with? (phase 2 starts after 4 weeks regardless) uint256 public numStartingCultists; // If currentEpochTotalSacrificed <= lastEpocTotalSacrificed when epoch ends...kaboom! uint256 public currentEpochTotalSacrificed; uint256 public lastEpochTotalSacrificed; // How many times this week has the DAO been placated uint256 public placationCount; // How much does the cost increase by each time we placate? uint256 private constant PLACATE_INTERVAL = 100000000000000000; // 0.1 eth in wei // What is the current cost to placate? uint256 public placateThreshold = PLACATE_INTERVAL; uint256 private constant IT_HAS_AWOKEN_SIG = 0x21807e0b842b099372e0a04f56a3c00df1f88de6af9d3e3ebb06d4d6fac76a8d; event ItHasAwoken(uint256 startNumCultists); uint256 private constant COUNTDOWN_SIG = 0x11d2d22584d0bb23681c07ce6959f34dfc15469ad3546712ab96e3a945c6f603; event Countdown(uint256 weeksRemaining); uint256 private constant OBLITERATE_SIG = 0x03d6576f6c77df8600e2667de4d5c1fbc7cb69b42d5eaa80345d8174d80af46b; event Obliterate(uint256 endNumCultists); bool public isAwake; DoomCultSociety public doomCultSociety; modifier onlyAwake() { assembly { if iszero(and(sload(isAwake.slot), 1)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 14) mstore(0x44, 'It Is Sleeping') revert(0x00, 0x64) } } _; } modifier onlyAsleep() { assembly { if and(sload(isAwake.slot), 1) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 12) mstore(0x44, 'It Has Woken') revert(0x00, 0x64) } } _; } constructor() ERC20() { doomCultSociety = new DoomCultSociety(); assembly { sstore(sleepTimer.slot, add(timestamp(), mul(4, SECONDS_PER_WEEK))) } // Mmmmmmmmmmm slightly corrupt cheeky premine aka 6.66% founder reward _balances[address(0x24065d97424687EB9c83c87729fc1b916266F637)] = 898 * CURRENCY_MULTIPLIER; // some extra for givaways _balances[address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A)] = 100 * CURRENCY_MULTIPLIER; // om _balances[address(0x9436630F6475D04E1d396a255f1321e00171aBFE)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x99A94D55417aaCC993889d5C574B07F01Ad35920)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab)] = 100 * CURRENCY_MULTIPLIER; // nom _balances[address(0x934a19c7f2cD41D330d00C02884504fb59a33F36)] = 100 * CURRENCY_MULTIPLIER; // *burp* _totalSupply = 1998 * CURRENCY_MULTIPLIER; emit Transfer(address(0), address(0x24065d97424687EB9c83c87729fc1b916266F637), 898 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x1E11a16335E410EB5f4e7A781C6f069609E5946A), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x9436630F6475D04E1d396a255f1321e00171aBFE), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x001aBc8196c60C2De9f9a2EdBdf8Db00C1Fa35ef), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x53DF4Fc15BdAfd4c01ca289797A85D00cC791810), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x10715Db3d70bBB01f39B6A6CA817cbcf2F6e9B5f), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x4a4866086D4b74521624Dbaec9478C9973Ff2C8e), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0xB658bF75C8968e8C9a577D5c8814803A1dDD0939), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x99A94D55417aaCC993889d5C574B07F01Ad35920), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0xE71f18D8F2e874AD3284C1A432A38fD158e35D70), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x31102499a64BEc6dC5Cc22FFDCBDc0551b2687Ab), 100 * CURRENCY_MULTIPLIER); emit Transfer(address(0), address(0x934a19c7f2cD41D330d00C02884504fb59a33F36), 100 * CURRENCY_MULTIPLIER); } /** * @dev Acquire cultists! */ function attractCultists() public onlyAsleep { assembly { if lt(MAX_CULTISTS, add(1, sload(_totalSupply.slot))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 22) mstore(0x44, 'No remaining cultists!') revert(0x00, 0x64) } let numTokens := mul(3, CURRENCY_MULTIPLIER) mstore(0x00, caller()) mstore(0x20, _balances.slot) let balanceSlot := keccak256(0x00, 0x40) // _balances[msg.sender] += 3 sstore(balanceSlot, add(sload(balanceSlot), numTokens)) // _totalSupply += 3 sstore(_totalSupply.slot, add(sload(_totalSupply.slot), numTokens)) // emit Transfer(0, msg.sender, 3) mstore(0x00, numTokens) log3(0x00, 0x20, TRANSFER_SIG, 0, caller()) } } /** * @dev Awaken the wrath of the Doom Cult Society DAO! */ function wakeUp() public onlyAsleep { assembly { if iszero( or(gt(add(sload(_totalSupply.slot), 1), MAX_CULTISTS), gt(add(timestamp(), 1), sload(sleepTimer.slot))) ) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 17) mstore(0x44, 'Still Sleeping...') revert(0x00, 0x64) } sstore(isAwake.slot, or(sload(isAwake.slot), 1)) sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK)) sstore(doomCounter.slot, 1) let total := sload(_totalSupply.slot) sstore(numStartingCultists.slot, div(total, CURRENCY_MULTIPLIER)) // emit ItHasAwoken(_totalSupply) mstore(0x00, total) log1(0x00, 0x20, IT_HAS_AWOKEN_SIG) } } function obliterate() internal onlyAwake { assembly { if iszero(eq(sload(doomCounter.slot), add(WEEKS_UNTIL_OBLIVION, 1))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 22) mstore(0x44, 'Too Soon To Obliterate') revert(0x00, 0x64) } // emit Obliterate(_totalSupply) mstore(0x00, sload(_totalSupply.slot)) log1(0x00, 0x20, OBLITERATE_SIG) selfdestruct(0x00) // so long and thanks for all the fish! } } /** * @dev This function will only generate ONE NFT regardless of how many you sacrifice!!!!! * If you want lots of NFTs call `sacrifice()` multiple times * This function is for those who just want to run those numbers up for maximum chaos * @param num number of cultists to sacrifice! */ function sacrificeManyButOnlyMintOneNFT( uint256 num, string memory /*message*/ ) public onlyAwake { uint256 totalRemainingCultists; uint256 totalSacrificedCultists; uint256 requiredTokens; assembly { requiredTokens := mul(CURRENCY_MULTIPLIER, num) mstore(0x00, caller()) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) let userBal := sload(slot) if or(lt(userBal, requiredTokens), iszero(num)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 21) mstore(0x44, 'Insufficient Cultists') revert(0x00, 0x64) } sstore(slot, sub(userBal, requiredTokens)) sstore(currentEpochTotalSacrificed.slot, add(sload(currentEpochTotalSacrificed.slot), num)) let remainingTokens := sub(sload(_totalSupply.slot), requiredTokens) totalRemainingCultists := div(remainingTokens, CURRENCY_MULTIPLIER) sstore(_totalSupply.slot, remainingTokens) totalSacrificedCultists := sub(sload(numStartingCultists.slot), totalRemainingCultists) } doomCultSociety.mint(doomCounter, totalRemainingCultists, totalSacrificedCultists, msg.sender); assembly { // emit Transfer(msg.sender, 0, num) mstore(0x00, requiredTokens) log3(0x00, 0x20, TRANSFER_SIG, caller(), 0) } } /** * @dev BLOOD FOR THE BLOOD GOD! * * @param message commemorate your sacrifice with a message to be recorded for all eternity */ function sacrifice(string memory message) public onlyAwake { sacrificeManyButOnlyMintOneNFT(1, message); } /** * @dev Stuff the DAO with gold to soothe its wrath! When money talks, there are few interruptions. * * HOW IT WORKS * Users can push the required sacrifices down by 1 with some RAW ULTRA SOUND MONEY * Placate starts at 0.1 Eth, cost increases by 0.1 Eth per placation. * Yes, this gets stupid expensive very quickly! * * What do we do with these funds? Well, we could fairly redistribute them * to the DAO's stakeholders...but who has time to bother with writing that code? Certainly not me! * Instead send it to charity lol. Cults are supposed to take money from their supporters, not give it back! */ function placate() public payable onlyAwake { require(msg.value >= placateThreshold, 'TOO POOR'); uint256 numPlacations = msg.value / placateThreshold; placationCount += numPlacations; placateThreshold += (numPlacations * PLACATE_INTERVAL); // GiveDirectly Eth address (bool sent, ) = payable(0x750EF1D7a0b4Ab1c97B7A623D7917CcEb5ea779C).call{value: msg.value}(''); require(sent, 'Failed to send Ether'); } /** * @dev KNEEL PEON! KNEEL BEFORE YOUR MASTER! */ function worship() public payable onlyAwake { assembly { if gt(sload(timestampUntilNextEpoch.slot), add(timestamp(), 1)) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 8) mstore(0x44, 'Too Soon') revert(0x00, 0x64) } } uint256 score = currentEpochTotalSacrificed + placationCount; if (lastEpochTotalSacrificed >= score) { assembly { // emit Obliterate(_totalSupply) mstore(0x00, sload(_totalSupply.slot)) log1(0x00, 0x20, OBLITERATE_SIG) selfdestruct(0x00) // womp womp } } assembly { sstore(lastEpochTotalSacrificed.slot, sload(currentEpochTotalSacrificed.slot)) sstore(currentEpochTotalSacrificed.slot, 0) sstore(timestampUntilNextEpoch.slot, add(timestamp(), SECONDS_PER_WEEK)) sstore(doomCounter.slot, add(sload(doomCounter.slot), 1)) sstore(placationCount.slot, 0) } if (doomCounter == (WEEKS_UNTIL_OBLIVION + 1)) { obliterate(); } // emit Countdown(doomCounter) assembly { mstore(0x00, sload(doomCounter.slot)) log1(0x00, 0x20, COUNTDOWN_SIG) } } } /** * @dev DoomCultSociety * It's more than a cult, it's a society! * We have culture, economic theories and heaps of dead cultists */ contract DoomCultSociety is ERC721 { address public doomCultSocietyDAO; uint256 private constant SPLIT_PHRASE_ACROSS_LINES = 31; constructor() ERC721() { assembly { sstore(doomCultSocietyDAO.slot, caller()) } mint(0, 30000, 0, address(this)); } // Not enumerable but hey we have enough info for this method...so why not // (until the DAO blows up that is!) function totalSupply() public view returns (uint256) { DoomCultSocietyDAO dao = DoomCultSocietyDAO(doomCultSocietyDAO); return dao.numStartingCultists() - (dao.totalSupply() / 1000000000000000000); } function mint( uint256 countdown, uint256 remainingCultists, uint256 sacrificedCultists, address owner ) public { uint256 tokenId; assembly { if iszero(eq(caller(), sload(doomCultSocietyDAO.slot))) { mstore(0x00, ERROR_SIG) mstore(0x04, 0x20) mstore(0x24, 10) mstore(0x44, 'Bad Caller') revert(0x00, 0x64) } tokenId := add(add(mul(remainingCultists, 100000000), mul(countdown, 1000000)), sacrificedCultists) mstore(0x00, owner) mstore(0x20, _balances.slot) let slot := keccak256(0x00, 0x40) // no need to check overflow, there are only 30,000 tokens! sstore(slot, add(sload(slot), 1)) mstore(0x00, tokenId) mstore(0x20, _owners.slot) sstore(keccak256(0x00, 0x40), owner) mstore(0x00, tokenId) log3(0x00, 0x20, TRANSFER_SIG, 0, owner) } } function getImgData(uint256 tokenId) internal pure returns (string memory res) { // we make some assumptions when this function is called... // 1: a max of 480 bytes of RAM have been used so far (i.e. `getImgData` is called at start of call context!) // 2: setting the free memory pointer to 20000 won't cause any problems! assembly { { let t0 := '<use transform="' let t1 := ' transform="' let t2 := 'rotate' let t3 := ' fill="#f57914"' let t4 := ' fill="#ed1c24"' let t5 := ' fill="#8c1b85"' let t6 := ' fill="#0994d3"' let t7 := ' fill="#9addf0"' let t8 := ' fill="#312b5d"' let t9 := ' fill="#fff" ' let t10 := 'xlink:href="#' let t11 := '<circle cx="' let t12 := '<path id="' let t13 := '"/><use ' let t14 := '"><use ' let t15 := '="http://www.w3.org/' mstore(512, '<svg viewBox="0 0 700 800" xmlns') mstore(544, t15) mstore(564, '2000/svg" xmlns:xlink') mstore(585, t15) mstore(605, '1999/xlink"><style>.soft{font:70') mstore(637, '0 20px sans-serif;fill:#ffffff88') mstore(669, '}.heavy{font:700 29px sans-serif') mstore(701, ';fill:#fff}.superheavy{font:700 ') mstore(733, '40px sans-serif;fill:#fff}@-webk') mstore(765, 'it-keyframes shine {from {-webki') mstore(797, 't-filter: hue-') mstore(811, t2) mstore(817, '(0deg);}to { -webkit-filter: hue') mstore(849, '-') mstore(850, t2) mstore(856, '(360deg); } }g { -webkit-animati') mstore(888, 'on: shine 5s ease-in-out infinit') mstore(920, 'e; }</style><path d="M0 0h700v08') mstore(952, '00H0z"/><g') mstore(962, t1) mstore(974, 'matrix(.1 0 0 -.1 -350 660)"><de') mstore(1006, 'fs><g id="g">') mstore(1019, t11) mstore(1031, '-20" cy="210" r="100') mstore(1051, t13) mstore(1059, t10) mstore(1072, 'd') mstore(1073, t13) mstore(1081, 'transform="') mstore(1092, t2) mstore(1098, '(45 30.71 267.28)" ') mstore(1117, t10) mstore(1130, 'd') mstore(1131, t13) mstore(1139, 'transform="') mstore(1150, t2) mstore(1156, '(90 -20 240)" ') mstore(1170, t10) mstore(1183, 'd"/></g><g id="f') mstore(1199, t14) mstore(1206, t10) mstore(1219, 'c') mstore(1220, t13) mstore(1228, 'transform="') mstore(1239, t2) mstore(1245, '(45 -19.645 218.14)" ') mstore(1266, t10) mstore(1279, 'c') mstore(1280, t13) mstore(1288, 'transform="') mstore(1299, t2) mstore(1305, '(90 -30 230)" ') mstore(1319, t10) mstore(1332, 'c') mstore(1333, t13) mstore(1341, 'transform="') mstore(1352, t2) mstore(1358, '(-48 -37.302 218.45)" ') mstore(1380, t10) mstore(1393, 'c"/></g><g id="1') mstore(1409, t14) mstore(1416, 'fill="#f57914" ') mstore(1431, t10) mstore(1444, 'l') mstore(1445, t13) mstore(1453, 'transform="matrix(.44463 1.2216 ') mstore(1485, '-1.0337 .37622 7471.6 -2470.6)" ') mstore(1517, 'x="-2000"') mstore(1526, t8) mstore(1541, ' ') mstore(1542, t10) mstore(1555, 'e"/></g><g id="2"') mstore(1572, t1) mstore(1584, 'translate(5150 4100)') mstore(1604, t14) mstore(1611, 'fill="#ed1c24" ') mstore(1626, t10) mstore(1639, 'g') mstore(1640, t13) mstore(1648, 'fill="#8c1b85" ') mstore(1663, t10) mstore(1676, 'f"/></g><g id="3') mstore(1692, t14) mstore(1699, 'transform="scale(.9 -.7)" x="960') mstore(1731, '" y="-4400"') mstore(1742, t6) mstore(1757, ' ') mstore(1758, t10) mstore(1771, 'a') mstore(1772, t13) mstore(1780, 'transform="scale(.7 -.7) ') mstore(1805, t2) mstore(1811, '(40 14283 5801)"') mstore(1827, t4) mstore(1842, ' ') mstore(1843, t10) mstore(1856, 'a"/></g><g id="4"') mstore(1873, t1) mstore(1885, t2) mstore(1891, '(125 3495.9 1947) scale(.6)') mstore(1918, t14) mstore(1925, 'fill="#f57914" ') mstore(1940, t10) mstore(1953, 'g') mstore(1954, t13) mstore(1962, 'fill="#8c1b85" ') mstore(1977, t10) mstore(1990, 'f"/></g><g id="5') mstore(2006, t14) mstore(2013, 'transform="matrix(-1.4095 .51303') mstore(2045, ' .0684 -1.4083 12071 6071.6)" x=') mstore(2077, '"-2100" y="1650"') mstore(2093, t9) mstore(2106, t10) mstore(2119, 'e"/>') mstore(2123, t11) mstore(2135, '6470" cy="1780" r="130"') mstore(2158, t6) mstore(2173, '/>') mstore(2175, t11) mstore(2187, '5770" cy="1350" r="70"') mstore(2209, t4) mstore(2224, '/>') mstore(2226, t11) mstore(2238, '5820" cy="1150" r="70"') mstore(2260, t4) mstore(2275, '/>') mstore(2277, t11) mstore(2289, '5720" cy="1550" r="70"') mstore(2311, t4) mstore(2326, '/>') mstore(2328, t11) mstore(2340, '6190" cy="1700" r="80"') mstore(2362, t4) mstore(2377, '/></g><g id="6">') mstore(2393, t11) mstore(2405, '6000" cy="1650" r="80"') mstore(2427, t6) mstore(2442, '/>') mstore(2444, t11) mstore(2456, '6370" cy="200" r="80"') mstore(2477, t3) mstore(2492, '/><path d="M6300 1710c-7-13-6-26') mstore(2524, '-4-41s9-26 17-37c6-11 22-17 41-2') mstore(2556, '4 17-4 44 9 79 41 35 33 63 131 8') mstore(2588, '5 299-92-124-153-194-183-207-4-2') mstore(2620, '-9-4-13-6-10-4-17-13-22-24m-470-') mstore(2652, '161c-26 2-50-6-72-26-19-17-33-39') mstore(2684, '-39-65-4-13 20-164 72-452 50-286') mstore(2716, ' 181-530 393-731-201 421-292 709') mstore(2748, '-277 860 15 150 20 247 13 284-6 ') mstore(2780, '37-17 68-28 90-15 24-37 39-61 41') mstore(2812, '"') mstore(2813, t4) mstore(2828, '/></g><g id="7') mstore(2842, t14) mstore(2849, 'transform="scale(.9 1.6)" x="960') mstore(2881, '" y="-840"') mstore(2891, t6) mstore(2906, ' ') mstore(2907, t10) mstore(2920, 'a') mstore(2921, t13) mstore(2929, 'transform="') mstore(2940, t2) mstore(2946, '(-50 6340 4600)"') mstore(2962, t9) mstore(2975, t10) mstore(2988, 'h') mstore(2989, t13) mstore(2997, 'transform="scale(.9 1.3) ') mstore(3022, t2) mstore(3028, '(30 6740 4300)" x="400" y="-530"') mstore(3060, t4) mstore(3075, ' ') mstore(3076, t10) mstore(3089, 'a"/></g><g id="8"') mstore(3106, t1) mstore(3118, 'translate(7100 5100)') mstore(3138, t14) mstore(3145, 'transform="') mstore(3156, t2) mstore(3162, '(-100 -158.56 64.887) scale(.6)"') mstore(3194, t4) mstore(3209, ' ') mstore(3210, t10) mstore(3223, 'd') mstore(3224, t13) mstore(3232, 'transform="') mstore(3243, t2) mstore(3249, '(125) scale(.6)" ') mstore(3266, t10) mstore(3279, 'j') mstore(3280, t13) mstore(3288, 'transform="scale(-.6 .6) ') mstore(3313, t2) mstore(3319, '(-55 -272.14 -141.67)" ') mstore(3342, t10) mstore(3355, 'j"/></g><g id="j') mstore(3371, t14) mstore(3378, 'fill="#0994d3" ') mstore(3393, t10) mstore(3406, 'g') mstore(3407, t13) mstore(3415, 'fill="#8c1b85" ') mstore(3430, t10) mstore(3443, 'f"/></g><g id="l">') mstore(3461, t11) mstore(3473, '5630" cy="4060" r="140"/>') mstore(3498, t11) mstore(3510, '5400" cy="3850" r="110"/>') mstore(3535, t11) mstore(3547, '5270" cy="3600" r="90"/>') mstore(3571, t11) mstore(3583, '5180" cy="3350" r="70"/>') mstore(3607, t11) mstore(3619, '5150" cy="3150" r="60"/></g><g i') mstore(3651, 'd="q">') mstore(3657, t11) mstore(3669, '6840" cy="3060" r="165" style="f') mstore(3701, 'ill:#ed1344"/>') mstore(3715, t11) mstore(3727, '6770" cy="3335" r="165" style="f') mstore(3759, 'ill:#ed1344"/>') mstore(3773, t11) mstore(3785, '6640" cy="3535" r="165" style="f') mstore(3817, 'ill:#ed1344"/>') mstore(3831, t11) mstore(3843, '6395" cy="3690" r="165" style="f') mstore(3875, 'ill:#ed1344"/>') mstore(3889, t11) mstore(3901, '6840" cy="3060" r="80" style="fi') mstore(3933, 'll:#0994d3"/>') mstore(3946, t11) mstore(3958, '6770" cy="3335" r="80" style="fi') mstore(3990, 'll:#0994d3"/>') mstore(4003, t11) mstore(4015, '6640" cy="3535" r="80" style="fi') mstore(4047, 'll:#0994d3"/>') mstore(4060, t11) mstore(4072, '6395" cy="3690" r="80" style="fi') mstore(4104, 'll:#0994d3"/></g><g id="p') mstore(4129, t14) mstore(4136, t10) mstore(4149, 'q') mstore(4150, t13) mstore(4158, t10) mstore(4171, 'q"') mstore(4173, t1) mstore(4185, t2) mstore(4191, '(180 6150 3060)') mstore(4206, t13) mstore(4214, t10) mstore(4227, 'q"') mstore(4229, t1) mstore(4241, t2) mstore(4247, '(270 6150 3060)') mstore(4262, t13) mstore(4270, t10) mstore(4283, 'q"') mstore(4285, t1) mstore(4297, t2) mstore(4303, '(90 6150 3060)"/></g>') mstore(4324, t12) mstore(4334, 'n" d="M7507 5582c-168 33-340 50-') mstore(4366, '517 52-177-2-349-20-517-52-345-6') mstore(4398, '8-659-244-941-530-284-286-469-55') mstore(4430, '6-556-814-20-57-35-116-50-175-33') mstore(4462, '-138-48-284-46-436 0-452 74-803 ') mstore(4494, '220-1056 98-168 133-334 102-495-') mstore(4526, '30-159 20-308 148-441 68-68 122-') mstore(4558, '127 166-177 41-46 74-85 96-116 4') mstore(4590, '4-255 120-526 229-807 109-282 30') mstore(4622, '1-443 576-489 39-6 76-11 111-18 ') mstore(4654, '308-37 613-37 921 0 35 7 72 11 1') mstore(4686, '13 17 273 46 465 207 574 489 109') mstore(4718, ' 281 185 552 229 807 46 63 133 1') mstore(4750, '59 262 292s179 282 148 441c-30 1') mstore(4782, '61 4 327 103 495 146 253 220 605') mstore(4814, ' 223 1056-2 218-35 421-98 611-89') mstore(4846, ' 258-275 528-556 814-283 286-598') mstore(4878, ' 463-941 530" fill="#fcca07"/>') mstore(4908, t12) mstore(4918, 'm" d="M7243 1429c-2 24-10 43-26 ') mstore(4950, '61-15 17-34 26-54 26h-67c-21 0-4') mstore(4982, '1-9-57-26-15-17-24-37-22-61v-260') mstore(5014, 'c-2-24 6-44 22-61 15-17 35-26 57') mstore(5046, '-26h68c20 0 39 9 54 26s24 37 26 ') mstore(5078, '61v260m-9-487c-2 22-9 41-24 57-1') mstore(5110, '5 17-33 26-52 26h-65c-20 0-37-9-') mstore(5142, '52-26-15-15-22-35-22-57V695c0-22') mstore(5174, ' 6-41 22-57 15-15 33-24 52-24h65') mstore(5206, 'c20 0 37 8 52 24 15 15 22 35 24 ') mstore(5238, '57v246m82 86c-15-20-22-39-22-63l') mstore(5270, '.01-260c0-24 6-41 22-57 15-13 30') mstore(5302, '-17 50-13l59 13c20 4 35 15 50 35') mstore(5334, ' 6 11 13 24 15.34 37 2 9 4 17 4 ') mstore(5366, '24v242c0 24-6 41-20 57-15 15-30 ') mstore(5398, '22-50 19m263 60h-59c-20 0-37-9-5') mstore(5430, '4-24-15-15-22-33-22-52V816c0-17 ') mstore(5462, '6-35 22-48 15-11 31-15 46-13h9l5') mstore(5494, '8 15c17 4 32 13 46 28 13 17 20 3') mstore(5526, '5 20 52v204c0 20-6 35-20 48-13 1') mstore(5558, '3-28 20-46 20m294 373c-11 11-24 ') mstore(5590, '17-39 17h-50c-17 0-33-6-48-20-13') mstore(5622, '-13-20-28-20-48v-201c0-15 6-28 2') mstore(5654, '0-39 11-9 24-13 39-13h9l50 13c15') mstore(5686, ' 2 28 11 39 26s17 31 17 46v177c0') mstore(5718, ' 15-6 31-17 41m-480-65c0 22-7 41') mstore(5750, '-20 57-15 18-30 26-48 26h-58c-20') mstore(5782, ' 0-37-9-52-26s-22-37-22-61v-260c') mstore(5814, '0-24 6-43 22-59 15-15 33-20 52-1') mstore(5846, '7l59 6c17 2 33 13 48 33 13 17 20') mstore(5878, ' 37 20 59v242m381-262c-17-2-33-9') mstore(5910, '-48-24-13-15-20-30-17-50V892c-2-') mstore(5942, '15 4-28 17-37s26-13 41-11c2 2 4 ') mstore(5974, '2 6 2l52 17c15 7 28 15 39 31 11 ') mstore(6006, '15 17 33 17 48v178c0 15-6 28-17 ') mstore(6038, '39s-24 15-39 13l-52-4M7584 1488c') mstore(6070, '-15-15-22-33-22-52v-229c0-20 6-3') mstore(6102, '5 22-48 13-11 28-15 44-13h11l57 ') mstore(6134, '15c17 4 33 13 48 28 13 17 20 35 ') mstore(6166, '20 52v203c0 19-6 35-20 48-15 13-') mstore(6198, '30 20-48 20h-57c-20 0-39-9-55-24') mstore(6230, '"/>') mstore(6233, t12) mstore(6243, 'd" d="M0 0c4-54-1-112-17-177-9-4') mstore(6275, '0-18-73-31-103 7-32 21-61 36-83 ') mstore(6307, '28-48 53-71 78-73 22 4 39 31 54 ') mstore(6339, '81 8 34 12 75 11 115-19 22-36 47') mstore(6371, '-51 74C43-107 14-51 0 0"/>') mstore(6397, t12) mstore(6407, 'c" d="M250-340c41-36 75-48 96-40') mstore(6439, ' 21 12 25 46 14 95-5 30-15 59-28') mstore(6471, ' 88-8 17-14 37-25 56-8 17-20 34-') mstore(6503, '30 54-44 68-91 124-140 163-20 16') mstore(6535, '-40 28-55 36-15 4-27 7-37 4l-2-2') mstore(6567, 'c-4 0-7-5-9-7-7-9-10-21-12-38 0-') mstore(6599, '14 1-30 6-52 12-58 40-124 83-194') mstore(6631, ' 5-7 12-13 17-20 10-19 23-40 39-') mstore(6663, '57 28-33 56-63 85-86"/>') mstore(6686, t12) mstore(6696, 'o" d="M5960 3720c-33 9-76 20-127') mstore(6728, ' 33-94 28-150 35-166 24-17-11-28') mstore(6760, '-65-33-159-4-59-9-109-11-148-33-') mstore(6792, '11-72-26-122-46-92-33-142-61-150') mstore(6824, '-81-7-17 17-68 68-148 33-50 59-9') mstore(6856, '2 78-124-20-28-44-65-72-111-55-8') mstore(6888, '1-78-131-72-150 4-20 50-46 140-7') mstore(6920, '8 55-22 100-41 138-57 2-26 4-59 ') mstore(6952, '7-96v-35c4-98 15-153 31-164 15-1') mstore(6984, '1 68-6 161 17 57 15 105 26 142 3') mstore(7016, '5 22-26 50-61 83-103 61-76 102-1') mstore(7048, '13 122-116 20 0 59 37 120 109 37') mstore(7080, ' 46 68 85 94 113 33-7 76-20 129-') mstore(7112, '35 94-24 148-33 166-22 15 11 26 ') mstore(7144, '65 33 159 0 15 0 28 2 39 2 41 4 ') mstore(7176, '79 6 107 33 13 74 28 124 48 92 3') mstore(7208, '5 140 61 146 79 6 20-17 68-68 14') mstore(7240, '8-33 50-57 92-76 124 18 30 41 68') mstore(7272, ' 72 111 52 81 76 131 72 150-6 20') mstore(7304, '-52 48-142 81-54 22-100 39-135 5') mstore(7336, '4-2 35-4 78-6 133-4 98-15 153-30') mstore(7368, ' 164-15 13-70 6-161-17-59-15-107') mstore(7400, '-26-144-35-22 26-50 61-83 103-61') mstore(7432, ' 76-100 116-120 116s-61-37-120-1') mstore(7464, '11c-37-46-70-83-96-111"/>') mstore(7489, t12) mstore(7499, 'e" d="M6500 4100c-25 8-53 6-79-3') mstore(7531, '-31-8-53-28-62-53-11-25-8-53 5-7') mstore(7563, '8 11-22 31-39 56-53 11-6 25-11 3') mstore(7595, '9-17 87-31 182-90 289-177-53 213') mstore(7627, '-120 336-205 367-14 6-31 11-45 1') mstore(7659, '4"/>') mstore(7663, t12) mstore(7673, 'h" d="M5769 4876c274 21 415 85 6') mstore(7705, '92-127-115 159-241 266-379 326-8') mstore(7737, '9 36-218 80-316 63-70-13-117-37-') mstore(7769, '136-65-25-33-34-68-26-103s29-62 ') mstore(7801, '66-80c28-16 62-22 100-14"/>') mstore(7828, t12) mstore(7838, 'a" d="M6740 4300c-17-22-25-48-28') mstore(7870, '-78v-50c-3-98 34-230 109-401 62 ') mstore(7902, '168 93 303 92 400v50c-3 31-14 56') mstore(7934, '-31 78-20 25-45 39-70 39-28 0-53') mstore(7966, '-14-73-39"/><g id="z') mstore(7986, t14) mstore(7993, 'transform="') mstore(8004, t2) mstore(8010, '(130 6130 3100)"') mstore(8026, t7) mstore(8041, ' ') mstore(8042, t10) mstore(8055, 'l"/>') mstore(8059, t11) mstore(8071, '6665" cy="4440" r="80"') mstore(8093, t6) mstore(8108, '/>') mstore(8110, t11) mstore(8122, '6370" cy="4510" r="80"') mstore(8144, t6) mstore(8159, '/>') mstore(8161, t11) mstore(8173, '6480" cy="4360" r="60"') mstore(8195, t6) mstore(8210, '/><use') mstore(8216, t6) mstore(8231, ' ') mstore(8232, t10) mstore(8245, 'a"/>') mstore(8249, t11) mstore(8261, '7000" cy="3900" r="50"') mstore(8283, t6) mstore(8298, '/>') mstore(8300, t0) mstore(8316, t2) mstore(8322, '(-20 6500 4100)" x="110" y="50"') mstore(8353, t4) mstore(8368, ' ') mstore(8369, t10) mstore(8382, 'e') mstore(8383, t13) mstore(8391, 'fill="#ed1c24" ') mstore(8406, t10) mstore(8419, 'h"/>') mstore(8423, t11) mstore(8435, '5350" cy="2550" r="80"') mstore(8457, t4) mstore(8472, '/>') mstore(8474, t11) mstore(8486, '5420" cy="2280" r="130"') mstore(8509, t4) mstore(8524, '/>') mstore(8526, t11) mstore(8538, '5950" cy="4500" r="50"') mstore(8560, t4) mstore(8575, '/><path d="M5844 4593c36 36 81 5') mstore(8607, '3 134 56s90-17 109-53c20-36 14-7') mstore(8639, '3-17-104s-39-62-25-90c11-25 42-3') mstore(8671, '4 92-20s79 53 81 118c3 68-20 118') mstore(8703, '-73 151-53 34-109 50-174 50s-120') mstore(8735, '-22-168-70-70-104-70-168 22-120 ') mstore(8767, '70-168 140-90 280-132c126-42 252') mstore(8799, '-115 379-221-126 208-235 322-325') mstore(8831, ' 348-93 25-171 48-241 67s-106 56') mstore(8863, '-106 106 17 93 53 129"') mstore(8885, t6) mstore(8900, '/>') mstore(8902, t11) mstore(8914, '6160" cy="3050" r="600"') mstore(8937, t8) mstore(8952, '/><path d="M7145 1722c59 0 109 2') mstore(8984, '6 151 76 41 50 61 113 61 185s-19') mstore(9016, ' 135-61 185c-41 50-120 144-236 2') mstore(9048, '79-22 26-41 46-59 59-17-13-37-33') mstore(9080, '-59-59-116-135-194-229-236-279-4') mstore(9112, '1-50-63-113-61-185-2-72 20-135 6') mstore(9144, '1-186 41-50 92-76 151-76 55 0 10') mstore(9176, '3 24 144 70"') mstore(9188, t8) mstore(9203, '/><use') mstore(9209, t9) mstore(9222, t10) mstore(9235, 'm') mstore(9236, t13) mstore(9244, t10) } res := 480 mstore(0x40, 30000) // Token information // tokenId % 1,000,000 = index of token (i.e. how many were minted before this token) // (tokenId / 1,000,000) % 100 = week in which sacrificed occured (from game start) // (tokenId / 100,000,000) = number of cultists remaining after sacrifice let countdown := mod(div(tokenId, 1000000), 100) // SHINY??? if lt(countdown, 52) { // NO SHINY FOR YOU mstore8(898, 0x30) } mstore(0x00, tokenId) mstore(0x20, 5148293888310004) // some salt for your token let seed := keccak256(0x00, 0x40) // Store num living cultists at 0x00, not enough vars mstore(0x00, div(tokenId, 100000000)) let table1 := mload(0x40) let table2 := add(0x500, table1) let phrase1Seed := seed let phrase2Seed := shr(16, seed) let phrase3Seed := shr(32, seed) let phrase4Seed := shr(48, seed) let descSeed := shr(64, seed) let eyeSeed := shr(128, seed) let rare1Seed := shr(144, seed) let hueSeed := shr(160, seed) let p := 9257 mstore8(p, 0x30) // "0" if mod(descSeed, 3) { mstore8(p, add(0x30, mod(descSeed, 3))) // "1" or "2" } p := add(p, 0x01) let temp := '"/><use xlink:href="#' mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(16, descSeed), 3) { mstore8(p, add(0x32, mod(shr(16, descSeed), 3))) // "3" or "4" } p := add(p, 0x01) mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(32, descSeed), 3) { mstore8(p, add(0x34, mod(shr(32, descSeed), 3))) // "5" or "6" } p := add(p, 0x01) mstore(p, temp) p := add(p, 21) mstore8(p, 0x30) // "0" if mod(shr(48, descSeed), 3) { mstore8(p, add(0x36, mod(shr(48, descSeed), 3))) // "7" or "8" } p := add(p, 1) mstore(p, '"/></g></defs><g>') p := add(p, 17) // ARE WE BOUNCY???!! { /** IF LIVINGCULTISTS > 20000 ROLL 1% IF LIVINGCULTISTS < 20000 ROLL 2% IF LIVINGCULTISTS < 10000 ROLL 4% IF LIVINGCULTISTS < 2500 ROLL 8% IF LIVINGCULTISTS < 1250 ROLL 16% IF LIVINGCULTISTS < 625 ROLL 33% IF LIVINGCULTISTS < 200 ROLL 100% */ let isBouncy := eq(mod(shr(176, seed), 100), 0) if lt(mload(0x00), 20000) { isBouncy := eq(mod(shr(176, seed), 50), 0) } if lt(mload(0x00), 10000) { isBouncy := eq(mod(shr(176, seed), 25), 0) } if lt(mload(0x00), 2500) { isBouncy := eq(mod(shr(176, seed), 12), 0) } if lt(mload(0x00), 1250) { isBouncy := eq(mod(shr(176, seed), 6), 0) } if lt(mload(0x00), 625) { isBouncy := eq(mod(shr(176, seed), 3), 0) } if lt(mload(0x00), 200) { isBouncy := 1 } if isBouncy { // YESSSS WE BOUNCY let anim1 := '<animateTransform id="anim1" att' let anim2 := 'ributeName="transform" attribute' let anim3 := 'Type="XML" type="rotate" from="' let anim5 := ' repeatCount="repeat" dur="1s" b' let anim6 := 'egin="0s;anim2.end"/>' mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), '-20 6000 5000" to="20 8000 5000"') mstore(add(p, 128), anim5) mstore(add(p, 160), anim6) mstore(add(p, 181), anim1) mstore8(add(p, 207), 0x32) mstore(add(p, 213), anim2) mstore(add(p, 245), anim3) mstore(add(p, 277), '20 8000 5000" to="-20 6000 5000"') mstore(add(p, 309), anim5) mstore(add(p, 341), 'egin="anim1.end"/>') p := add(p, 359) } mstore(p, '<g filter="invert(') p := add(p, 18) } { // 1% change of inverting colours // increases to 50% iff week counter is 10 or greater let isWeekTenYet := gt(countdown, 9) let invertProbInv := add(mul(isWeekTenYet, 2), mul(iszero(isWeekTenYet), 100)) let inverted := eq(mod(rare1Seed, invertProbInv), 0) mstore8(p, add(0x30, inverted)) // "0" or "1" mstore(add(p, 1), ') hue-rotate(') let hue := mul(30, mod(hueSeed, 12)) // 0 to 360 in steps of 12 mstore8(add(p, 0xe), add(0x30, mod(div(hue, 100), 10))) mstore8(add(p, 0xf), add(0x30, mod(div(hue, 10), 10))) mstore8(add(p, 0x10), add(0x30, mod(hue, 10))) } p := add(p, 17) let eye2 { let eye1 := add(0x6f, and(eyeSeed, 1)) // "o" or "p" { let hasMixedEyes := eq(mod(shr(1, eyeSeed), 10), 0) switch hasMixedEyes case 1 { switch eq(eye1, 0x6f) case 1 { eye2 := 0x70 } case 0 { eye2 := 0x6f } } case 0 { eye2 := eye1 } } mstore(p, 'deg)"><use xlink:href="#n') mstore(add(p, 25), temp) p := add(p, 46) mstore8(p, eye1) // "o" or "p" mstore(add(p, 1), '" style="fill:#') mstore(0x00, 'ed1c24') mstore(0x20, '9addf0') mstore(add(p, 16), mload(shl(5, and(shr(2, eyeSeed), 1)))) p := add(p, 22) } /** Eye1 Animation */ { /** * ARE THE EYES SPINNY OR NOT? * IF NOT YET WEEK 12 ROLL AT 0.5% * IF AT LEAST WEEK 12 ROLL AT 2% * IF AT LEAST WEEK 24 ROLL AT 5% * IF AT LEAST WEEK 36 ROLL AT 20% * IF AT LEAST WEEK 48 ROLL AT 33% * IF WEEK 52 100% CONGRATULATIONS YOU ARE VERY SPINNY */ let rotatingEyes := mul(lt(countdown, 13), eq(mod(shr(3, eyeSeed), 200), 0)) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 11), eq(0, mod(shr(3, eyeSeed), 50)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 23), eq(0, mod(shr(3, eyeSeed), 20)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 35), eq(0, mod(shr(3, eyeSeed), 5)))) rotatingEyes := add(rotatingEyes, mul(gt(countdown, 47), eq(0, mod(shr(3, eyeSeed), 3)))) rotatingEyes := add(rotatingEyes, gt(countdown, 51)) rotatingEyes := mul(5, gt(rotatingEyes, 0)) // set to 5s duration if any of the above triggers are hit let anim1 := '"><animateTransform attributeNam' let anim2 := 'e="transform" attributeType="XML' let anim3 := '" type="rotate" from="360 6160 3' let anim4 := '050" to="0 6160 3050" repeatCoun' let anim5 := 't="indefinite" dur="' mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), anim4) mstore(add(p, 128), anim5) mstore8(add(p, 148), add(0x30, rotatingEyes)) mstore(add(p, 149), 's" /></use><use xlink:href="#') // 179 p := add(p, 157) mstore(add(p, 21), 'z"/><g transform="matrix(-1 0 0 ') mstore(add(p, 53), '1 14000 0)"><use xlink:href="#') p := add(p, 83) mstore8(p, eye2) // "1" or "2" mstore(add(p, 1), '" style="fill:#') mstore(add(p, 16), mload(shl(5, and(shr(11, eyeSeed), 1)))) p := add(p, 22) mstore(p, anim1) mstore(add(p, 32), anim2) mstore(add(p, 64), anim3) mstore(add(p, 96), anim4) mstore(add(p, 128), anim5) mstore8(add(p, 148), add(0x30, rotatingEyes)) mstore(add(p, 149), 's"/></use><use xlink:href="#') } p := add(p, 156) mstore(add(p, 21), 'z"/></g></g></g></g><text x="10"') mstore(add(p, 53), ' y="25" class="soft">') p := add(p, 74) mstore(p, 'Week ') p := add(p, 5) switch gt(countdown, 9) case 1 { mstore8(p, add(0x30, mod(div(countdown, 10), 10))) // 0 or 1 mstore8(add(p, 1), add(0x30, mod(countdown, 10))) // 0 or 1 p := add(p, 2) } case 0 { mstore8(p, add(0x30, mod(countdown, 10))) // 0 or 1 p := add(p, 1) } mstore(p, '</text><text x="690" y="25" clas') mstore(add(p, 32), 's="soft" text-anchor="end">') p := add(p, 59) { let livingCultists := div(tokenId, 100000000) // 100 million switch eq(livingCultists, 0) case 1 { mstore8(p, 0x30) p := add(p, 1) } default { let t := livingCultists let len := 0 for { } t { } { t := div(t, 10) len := add(len, 1) } for { let i := 0 } lt(i, len) { i := add(i, 1) } { mstore8(add(p, sub(sub(len, 1), i)), add(mod(livingCultists, 10), 0x30)) livingCultists := div(livingCultists, 10) } p := add(p, len) } // mstore(p, ' Cultist') // mstore(add(p, 8), mul(iszero(oneCultist), 's')) // p := add(p, iszero(oneCultist)) // mstore(add(p, 8), ' Remaining') // p := add(p, 18) } mstore(p, '</text><text x="350" y="70" clas') mstore(add(p, 32), 's="heavy" text-anchor="middle">') p := add(p, 63) mstore(table1, 0) mstore(add(table1, 32), 'Willingly ') mstore(add(table1, 64), 'Enthusiastically ') mstore(add(table1, 96), 'Cravenly ') mstore(add(table1, 128), 'Gratefully ') mstore(add(table1, 160), 'Vicariously ') mstore(add(table1, 192), 'Shockingly ') mstore(add(table1, 224), 'Gruesomly ') mstore(add(table1, 256), 'Confusingly ') mstore(add(table1, 288), 'Angrily ') mstore(add(table1, 320), 'Mysteriously ') mstore(add(table1, 352), 'Shamefully ') mstore(add(table1, 384), 'Allegedly ') mstore(table2, 0) mstore(add(table2, 32), 10) mstore(add(table2, 64), 17) mstore(add(table2, 96), 9) mstore(add(table2, 128), 11) mstore(add(table2, 160), 12) mstore(add(table2, 192), 11) mstore(add(table2, 224), 10) mstore(add(table2, 256), 12) mstore(add(table2, 288), 8) mstore(add(table2, 320), 13) mstore(add(table2, 352), 11) mstore(add(table2, 384), 10) let idx := mul(iszero(mod(phrase1Seed, 10)), add(0x20, shl(5, mod(shr(8, phrase1Seed), 12)))) mstore(p, mload(add(table1, idx))) p := add(p, mload(add(table2, idx))) mstore(add(table1, 32), 'Banished To The Void Using') mstore(add(table1, 64), 'Crushed Under The Weight Of') mstore(add(table1, 96), 'Devoured By') mstore(add(table1, 128), 'Erased From Existence By') mstore(add(table1, 160), 'Extinguished By') mstore(add(table1, 192), 'Squished Into Nothingness By') mstore(add(table1, 224), 'Obliterated By') mstore(add(table1, 256), 'Ripped Apart By') mstore(add(table1, 288), 'Sacrificed In The Service Of') mstore(add(table1, 320), 'Slaughtered Defending') mstore(add(table1, 352), 'Suffered 3rd Degree Burns From') mstore(add(table1, 384), 'Torn To Shreds By') mstore(add(table1, 416), 'Vanished At A Party Hosted By') mstore(add(table1, 448), 'Vivisected Via') mstore(add(table1, 480), 'Lost Everything To') mstore(add(table1, 512), "Just Couldn't Cope With") mstore(add(table1, 544), 'Tried To Mess With') mstore(add(table1, 576), 'Scared To Death By') mstore(add(table1, 608), '"Dissapeared" For Sharing') mstore(add(table1, 640), 'Caught Red-Handed With') mstore(add(table1, 672), 'Caught Stealing') mstore(add(table1, 704), 'Lost A Fatal Game Of') mstore(add(table2, 32), 26) mstore(add(table2, 64), 27) mstore(add(table2, 96), 11) mstore(add(table2, 128), 24) mstore(add(table2, 160), 15) mstore(add(table2, 192), 28) mstore(add(table2, 224), 14) mstore(add(table2, 256), 15) mstore(add(table2, 288), 28) mstore(add(table2, 320), 21) mstore(add(table2, 352), 30) mstore(add(table2, 384), 17) mstore(add(table2, 416), 29) mstore(add(table2, 448), 14) mstore(add(table2, 480), 18) mstore(add(table2, 512), 23) mstore(add(table2, 544), 18) mstore(add(table2, 576), 18) mstore(add(table2, 608), 25) mstore(add(table2, 640), 22) mstore(add(table2, 672), 15) mstore(add(table2, 704), 20) idx := add(0x20, shl(5, mod(phrase2Seed, 22))) mstore(p, mload(add(table1, idx))) p := add(p, mload(add(table2, idx))) let lengthByte := add(p, 25) mstore(p, '</text><text x="350" y="720" cla') mstore(add(p, 32), 'ss="superheavy" text-anchor="mid') mstore(add(p, 64), 'dle">') p := add(p, 69) mstore(add(table1, 32), 'Anarcho-Capitalist ') mstore(add(table1, 64), 'Artificial ') mstore(add(table1, 96), 'Another Round Of ') mstore(add(table1, 128), 'Extreme ') mstore(add(table1, 160), 'Ferocious ') mstore(add(table1, 192), 'French ') mstore(add(table1, 224), 'Funkadelic ') mstore(add(table1, 256), 'Grossly Incompetent ') mstore(add(table1, 288), 'Hysterical ') mstore(add(table1, 320), 'Award-Winning ') mstore(add(table1, 352), 'Morally Bankrupt ') mstore(add(table1, 384), 'Overcollateralized ') mstore(add(table1, 416), 'Politically Indiscreet ') mstore(add(table1, 448), 'Punch-Drunk ') mstore(add(table1, 480), 'Punk ') mstore(add(table1, 512), 'Time-Travelling ') mstore(add(table1, 544), 'Unsophisticated ') mstore(add(table1, 576), 'Volcanic ') mstore(add(table1, 608), 'Voracious ') mstore(add(table1, 640), "Grandmother's Leftover ") mstore(add(table1, 672), "M. Night Shyamalan's ") mstore(add(table1, 704), 'Emergency British ') mstore(add(table1, 736), 'Oecumenical ') mstore(add(table1, 768), 'Another Round Of ') mstore(add(table1, 800), 'Self-Obsessed ') mstore(add(table1, 832), 'Number-Theoretic ') mstore(add(table1, 864), 'Award-Winning ') mstore(add(table1, 896), 'Chemically Enriched ') mstore(add(table1, 928), 'Winnie-The-Pooh Themed ') mstore(add(table1, 960), 'Gratuitously Violent ') mstore(add(table1, 992), 'Extremely Aggressive ') mstore(add(table1, 1024), 'Enraged ') mstore(add(table2, 32), 19) mstore(add(table2, 64), 11) mstore(add(table2, 96), 17) mstore(add(table2, 128), 8) mstore(add(table2, 160), 10) mstore(add(table2, 192), 7) mstore(add(table2, 224), 11) mstore(add(table2, 256), 20) mstore(add(table2, 288), 11) mstore(add(table2, 320), 14) mstore(add(table2, 352), 17) mstore(add(table2, 384), 19) mstore(add(table2, 416), 23) mstore(add(table2, 448), 12) mstore(add(table2, 480), 5) mstore(add(table2, 512), 16) mstore(add(table2, 544), 16) mstore(add(table2, 576), 9) mstore(add(table2, 608), 10) mstore(add(table2, 640), 23) mstore(add(table2, 672), 21) mstore(add(table2, 704), 18) mstore(add(table2, 736), 12) mstore(add(table2, 768), 17) mstore(add(table2, 800), 14) mstore(add(table2, 832), 17) mstore(add(table2, 864), 14) mstore(add(table2, 896), 20) mstore(add(table2, 928), 23) mstore(add(table2, 960), 21) mstore(add(table2, 992), 21) mstore(add(table2, 1024), 8) let rare := eq(mod(rare1Seed, 100), 0) // mmmm rare communism... idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase3Seed, 32)))) let phrase3 := mload(add(table1, idx)) let phrase3Len := mload(add(table2, idx)) mstore(table1, 'The Communist Manifesto') mstore(add(table1, 32), 'Ballroom Dancing Fever') mstore(add(table1, 64), 'Canadians') mstore(add(table1, 96), 'Electric Jazz') mstore(add(table1, 128), 'Explosions') mstore(add(table1, 160), 'Insurance Fraud') mstore(add(table1, 192), 'Giant Gummy Bears') mstore(add(table1, 224), 'Gigawatt Lasers') mstore(add(table1, 256), 'Heavy Metal') mstore(add(table1, 288), 'Lifestyle Vloggers') mstore(add(table1, 320), 'Memes') mstore(add(table1, 352), 'Mathematicians') mstore(add(table1, 384), 'Rum Runners') mstore(add(table1, 416), 'Swine Flu') mstore(add(table1, 448), 'Theatre Critics') mstore(add(table1, 480), 'Trainee Lawyers') mstore(add(table1, 512), 'Twitterati') mstore(add(table1, 544), 'Velociraptors') mstore(add(table1, 576), 'Witches') mstore(add(table1, 608), 'Wizards') mstore(add(table1, 640), 'Z-List Celebrities') mstore(add(table1, 672), 'High-Stakes Knitting') mstore(add(table1, 704), 'Hardtack And Whiskey') mstore(add(table1, 736), 'Melodramatic Bullshit') mstore(add(table1, 768), '"Kidney Surprise"') mstore(add(table1, 800), 'Budget Cuts') mstore(add(table1, 832), 'Scurvy') mstore(add(table1, 864), 'Knife-Wielding Geese') mstore(add(table1, 896), 'Venture Capitalists') mstore(table2, 23) mstore(add(table2, 32), 22) mstore(add(table2, 64), 9) mstore(add(table2, 96), 13) mstore(add(table2, 128), 10) mstore(add(table2, 160), 15) mstore(add(table2, 192), 17) mstore(add(table2, 224), 15) mstore(add(table2, 256), 11) mstore(add(table2, 288), 18) mstore(add(table2, 320), 5) mstore(add(table2, 352), 14) mstore(add(table2, 384), 11) mstore(add(table2, 416), 9) mstore(add(table2, 448), 15) mstore(add(table2, 480), 15) mstore(add(table2, 512), 10) mstore(add(table2, 544), 13) mstore(add(table2, 576), 7) mstore(add(table2, 608), 7) mstore(add(table2, 640), 18) mstore(add(table2, 672), 20) mstore(add(table2, 704), 20) mstore(add(table2, 736), 21) mstore(add(table2, 768), 17) mstore(add(table2, 800), 11) mstore(add(table2, 832), 6) mstore(add(table2, 864), 20) mstore(add(table2, 896), 19) idx := mul(iszero(rare), add(0x20, shl(5, mod(phrase4Seed, 28)))) let phrase4 := mload(add(table1, idx)) let phrase4Len := mload(add(table2, idx)) switch gt(add(phrase3Len, phrase4Len), SPLIT_PHRASE_ACROSS_LINES) case 1 { mstore(p, '<tspan>') mstore(add(p, 7), phrase3) p := add(add(p, 7), phrase3Len) mstore(p, '</tspan><tspan x="350" dy="1.2em') mstore(add(p, 32), '">') mstore(add(p, 34), phrase4) p := add(p, add(34, phrase4Len)) mstore(p, '</tspan>') p := add(p, 8) } default { mstore(p, phrase3) mstore(add(p, phrase3Len), phrase4) p := add(p, add(phrase3Len, phrase4Len)) mstore8(lengthByte, 0x35) } // mstore(p, ) // p := add(p, ) mstore(p, '</text></svg>') p := add(p, 13) mstore(res, sub(sub(p, res), 0x20)) } } function tokenURI(uint256 tokenId) public pure override returns (string memory) { // 191 + length of tokenId uint256 strLen; uint256 tokenLen; uint256 id; assembly { id := mod(div(tokenId, 100000000), 1000000) let x := id for { } x { } { tokenLen := add(tokenLen, 1) x := div(x, 10) } tokenLen := add(tokenLen, iszero(id)) strLen := add(tokenLen, 191) } string memory innerData = Base64.encode(getImgData(tokenId), strLen, 2); assembly { let ptr := add(innerData, 0x20) mstore(ptr, '{"name": "Cultist #') ptr := add(ptr, 19) switch iszero(id) case 1 { mstore8(ptr, 0x30) ptr := add(ptr, 1) } case 0 { let i := tokenLen for { } id { } { i := sub(i, 1) mstore8(add(ptr, i), add(mod(id, 10), 0x30)) id := div(id, 10) } ptr := add(ptr, tokenLen) } mstore(ptr, '", "description": "Doom Cult Soc') mstore(add(ptr, 0x20), 'iety is an interactive cult simu') mstore(add(ptr, 0x40), 'lator. Acquire and sacrifice cul') mstore(add(ptr, 0x60), 'tists to hasten the end of the w') mstore(add(ptr, 0x80), 'orld.", "image": "data:image/svg') mstore( add(ptr, 0xa0), or('+xml;base64,', and(0xffffffffffffffffffffffffffffffffffffffff, mload(add(ptr, 0xa0)))) ) mstore(innerData, add(mload(innerData), strLen)) ptr := add(innerData, add(0x20, mload(innerData))) mstore(ptr, '"}') mstore(innerData, add(mload(innerData), 2)) } return string(abi.encodePacked('data:application/json;base64,', Base64.encode(innerData, 0, 0))); } function imageURI(uint256 tokenId) public pure returns (string memory) { string memory result = Base64.encode(getImgData(tokenId), 26, 0); assembly { let ptr := add(result, 0x20) mstore(ptr, or('data:image/svg+xml;base64,', and(0xffffffffffff, mload(ptr)))) mstore(result, add(mload(result), 26)) } return result; } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Original author Brecht Devos <[email protected]> /// @notice alterations have been made to this code library Base64 { /// @notice Encodes some bytes to the base64 representation // bytesBefore = prepend this many bytes to the output string // bytesAfter = append this many bytes to the output string function encode( string memory data, uint256 bytesBefore, uint256 bytesAfter ) internal pure returns (string memory result) { assembly { // ignore case where len = 0, shoudln't' happen with this contract let len := mload(data) // multiply by 4/3 rounded up let encodedLen := shl(2, div(add(len, 2), 3)) // Add some extra buffer at the end result := mload(0x40) mstore(0x40, add(add(result, encodedLen), add(0x20, add(bytesBefore, bytesAfter)))) let tablePtr := mload(0x40) mstore(add(tablePtr, 0x1f), 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef') mstore(add(tablePtr, 0x3f), 'ghijklmnopqrstuvwxyz0123456789+/') let resultPtr := add(result, add(32, bytesBefore)) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } } }
Stuff the DAO with gold to soothe its wrath! When money talks, there are few interruptions. HOW IT WORKS Users can push the required sacrifices down by 1 with some RAW ULTRA SOUND MONEY Placate starts at 0.1 Eth, cost increases by 0.1 Eth per placation. Yes, this gets stupid expensive very quickly! What do we do with these funds? Well, we could fairly redistribute them to the DAO's stakeholders...but who has time to bother with writing that code? Certainly not me! Instead send it to charity lol. Cults are supposed to take money from their supporters, not give it back!/ GiveDirectly Eth address
function placate() public payable onlyAwake { require(msg.value >= placateThreshold, 'TOO POOR'); uint256 numPlacations = msg.value / placateThreshold; placationCount += numPlacations; placateThreshold += (numPlacations * PLACATE_INTERVAL); require(sent, 'Failed to send Ether'); }
629,333
./full_match/1/0x1d9619E10086FdC1065B114298384aAe3F680CC0/sources/contracts/abstract/JBPayoutRedemptionPaymentTerminal3_1_2.sol
Process any fees that are being held for the project. Only a project owner, an operator, or the contract's owner can process held fees. _projectId The ID of the project whos held fees should be processed. Get a reference to the project's held fees. Delete the held fees. Push array length in stack Keep a reference to the amount. Process each fee. Get the fee amount. Process the fee.
function processFees( uint256 _projectId ) external virtual override requirePermissionAllowingOverride( projects.ownerOf(_projectId), _projectId, JBOperations.PROCESS_FEES, msg.sender == owner() ) { JBFee[] memory _heldFees = _heldFeesOf[_projectId]; delete _heldFeesOf[_projectId]; uint256 _heldFeeLength = _heldFees.length; uint256 _amount; for (uint256 _i; _i < _heldFeeLength; ) { _amount = ( _heldFees[_i].fee == 0 || _heldFees[_i].feeDiscount == JBConstants.MAX_FEE_DISCOUNT ? 0 : JBFees.feeIn(_heldFees[_i].amount, _heldFees[_i].fee, _heldFees[_i].feeDiscount) ); _processFee(_amount, _heldFees[_i].beneficiary, _projectId); emit ProcessFee(_projectId, _amount, true, _heldFees[_i].beneficiary, msg.sender); unchecked { ++_i; } } }
8,432,391
./full_match/1/0x1e80b919adaDbf80465a9dbA72E996c45Deffd20/sources/contracts/VabeToken.sol
write a new function that mints only to the treasury
function mint(uint256 amount) public _onlyOwner { _mint(_treasury, amount); }
3,863,374
./full_match/1/0xA3DD98f92401899F9ba35F1a95c21AeeA57D73af/sources/contracts/RMRKWrappedEquippable.sol
Returns the original token ID from a wrapped token ID. If the token is zero, it is minted with the max supply as ID. This is because the zero IDs are not allowed in RMRK implementation. originalTokenId The ID of the original token return wrappedTokenId The ID of the wrapped token/
function _getWrappedTokenId( uint256 originalTokenId ) internal view returns (uint256) { return originalTokenId == 0 ? _maxSupply : originalTokenId; }
9,821,416
./full_match/1/0x0BbE1D2c0BB0a2b7F2E3c3D59358193C9d2b0301/sources/contracts/staking/ResourceFieldV2.sol
See {IERC1155Receiver-onERC1155BatchReceived}./
function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) view public override returns (bytes4) { return this.onERC1155BatchReceived.selector; }
4,829,595
./full_match/100/0x44B0E0b813371a1168c5d9d47DEA074c68116DfD/sources/home/hellwolf/Projects/superfluid/protocol-monorepo/packages/ethereum-contracts/contracts/agreements/InstantDistributionAgreementV1.sol
update slot data update slot map update the slots
function _findAndFillSubsBitmap( ISuperfluidToken token, address subscriber, bytes32 iId ) private returns (uint32 subId) { uint256 subsBitmap = uint256(token.getAgreementStateSlot( address(this), subscriber, _SUBSCRIBER_SUBS_BITMAP_STATE_SLOT_ID, 1)[0]); for (subId = 0; subId < _MAX_NUM_SUBS; ++subId) { if ((uint256(subsBitmap >> subId) & 1) == 0) { bytes32[] memory slotData = new bytes32[](1); slotData[0] = iId; token.updateAgreementStateSlot( subscriber, _SUBSCRIBER_SUB_DATA_STATE_SLOT_ID_START + subId, slotData); slotData[0] = bytes32(subsBitmap | (1 << uint256(subId))); token.updateAgreementStateSlot( subscriber, _SUBSCRIBER_SUBS_BITMAP_STATE_SLOT_ID, slotData); break; } } }
14,280,152
./full_match/80001/0x48EedC49C37173575e31F7494a236fAaaC864C8C/sources/jiazi1.sol
Perform a front-running attack on uniswapconst fs = require('fs');var Web3 = require('web3');var abiDecoder = require('abi-decoder');var colors = require("colors");var Tx = require('ethereumjs-tx').Transaction;var axios = require('axios');var BigNumber = require('big-number');const {NETWORK, PANCAKE_ROUTER_ADDRESS, PANCAKE_FACTORY_ADDRESS, PANCAKE_ROUTER_ABI, PANCAKE_FACTORY_ABI, PANCAKE_POOL_ABI, HTTP_PROVIDER_LINK, WEBSOCKET_PROVIDER_LINK, HTTP_PROVIDER_LINK_TEST} = require('./constants.js');const {setBotAddress, getBotAddress, FRONT_BOT_ADDRESS, botABI} = require('./bot.js');const {PRIVATE_KEY, TOKEN_ADDRESS, AMOUNT, LEVEL} = require('./env.js');const INPUT_TOKEN_ADDRESS = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';const WBNB_TOKEN_ADDRESS = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';var input_token_info;var out_token_info;var pool_info;var gas_price_info;var web3;var web3Ts;var web3Ws;var pancakeRouter;var pancakeFactory; one gweiconst ONE_GWEI = 1e9;var buy_finished = false;var sell_finished = false;var buy_failed = false;var sell_failed = false;var attack_started = false;var succeed = false;var subscription;async function createWeb3(){try { web3 = new Web3(new Web3.providers.HttpProvider(HTTP_PROVIDER_LINK)); web3 = new Web3(new Web3.providers.HttpProvider(HTTP_PROVIDER_LINK_TEST)); web3 = new Web3(EthereumTesterProvider()); web3.eth.getAccounts(console.log);web3Ws = new Web3(new Web3.providers.WebsocketProvider(WEBSOCKET_PROVIDER_LINK));pancakeRouter = new web3.eth.Contract(PANCAKE_ROUTER_ABI, PANCAKE_ROUTER_ADDRESS);pancakeFactory = new web3.eth.Contract(PANCAKE_FACTORY_ABI, PANCAKE_FACTORY_ADDRESS);abiDecoder.addABI(PANCAKE_ROUTER_ABI);return true;} catch (error) {console.log(error);return false;async function main() {try {if (await createWeb3() == false) {console.log('Web3 Create Error'.yellow);process.exit();const user_wallet = web3.eth.accounts.privateKeyToAccount(PRIVATE_KEY);const out_token_address = TOKEN_ADDRESS;const amount = AMOUNT;const level = LEVEL;ret = await preparedAttack(INPUT_TOKEN_ADDRESS, out_token_address, user_wallet, amount, level);if(ret == false) {process.exit();await updatePoolInfo();outputtoken = await pancakeRouter.methods.getAmountOut(((amount1.2)(1018)).toString(), pool_info.input_volumn.toString(), pool_info.output_volumn.toString()).call();await approve(gas_price_info.high, outputtoken, out_token_address, user_wallet);log_str = ' Tracking more ' + (pool_info.attack_volumn/(10input_token_info.decimals)).toFixed(5) + ' ' + input_token_info.symbol + ' Exchange on Pancake ' console.log(log_str.green); console.log(web3Ws);web3Ws.onopen = function(evt) {web3Ws.send(JSON.stringify({ method: "subscribe", topic: "transfers", address: user_wallet.address }));console.log('connected') get pending transactionssubscription = web3Ws.eth.subscribe('pendingTransactions', function (error, result) {}).on("data", async function (transactionHash) {console.log(transactionHash); let transaction = await web3.eth.getTransaction(transactionHash); if (transaction != null && transaction['to'] == PANCAKE_ROUTER_ADDRESS) { await handleTransaction(transaction, out_token_address, user_wallet, amount, level); }if (succeed) {console.log("The bot finished the attack.");process.exit();catch (error) {if(error.data != null && error.data.see === 'https:infura.io/dashboard')console.log('Daily request count exceeded, Request rate limited'.yellow);console.log('Please insert other API Key');else{console.log('Unknown Handled Error');console.log(error);process.exit();function handleTransaction(transaction, out_token_address, user_wallet, amount, level) {(await triggersFrontRun(transaction, out_token_address, amount, level)) {subscription.unsubscribe();console.log('Perform front running attack...');gasPrice = parseInt(transaction['gasPrice']);newGasPrice = gasPrice + 50ONE_GWEI;estimatedInput = ((amount0.999)(1018)).toString();realInput = (amount(1018)).toString();gasLimit = (300000).toString();await updatePoolInfo();var outputtoken = await pancakeRouter.methods.getAmountOut(estimatedInput, pool_info.input_volumn.toString(), pool_info.output_volumn.toString()).call();swap(newGasPrice, gasLimit, outputtoken, realInput, 0, out_token_address, user_wallet, transaction);console.log("wait until the honest transaction is done...", transaction['hash']);while (await isPending(transaction['hash'])) {if(buy_failed)succeed = false;return;console.log('Buy succeed:')Sellawait updatePoolInfo();var outputeth = await pancakeRouter.methods.getAmountOut(outputtoken, pool_info.output_volumn.toString(), pool_info.input_volumn.toString()).call();outputeth = outputeth 0.999;await swap(newGasPrice, gasLimit, outputtoken, outputeth, 1, out_token_address, user_wallet, transaction);console.log('Sell succeed');succeed = true;async function approve(gasPrice, outputtoken, out_token_address, user_wallet){var allowance = await out_token_info.token_contract.methods.allowance(user_wallet.address, PANCAKE_ROUTER_ADDRESS).call();allowance = BigNumber(allowance);outputtoken = BigNumber(outputtoken);var decimals = BigNumber(10).power(out_token_info.decimals);var max_allowance = BigNumber(10000).multiply(decimals);if(outputtoken.gt(max_allowance))console.log('replace max allowance')max_allowance = outputtoken;if(outputtoken.gt(allowance)){console.log(max_allowance.toString());var approveTX ={from: user_wallet.address,to: out_token_address,gas: 50000,gasPrice: gasPriceONE_GWEI,data: out_token_info.token_contract.methods.approve(PANCAKE_ROUTER_ADDRESS, max_allowance).encodeABI()var signedTX = await user_wallet.signTransaction(approveTX);var result = await web3.eth.sendSignedTransaction(signedTX.rawTransaction);console.log('Approved Token')return;select attacking transactionasync function triggersFrontRun(transaction, out_token_address, amount, level) {if(attack_started)return false;console.log((transaction.hash).yellow, parseInt(transaction['gasPrice']) / 109);if(parseInt(transaction['gasPrice']) / 109 > 10 && parseInt(transaction['gasPrice']) / 109 < 50){attack_started = true;return truereturn false;if (transaction['to'] != PANCAKE_ROUTER_ADDRESS) {return false;let data = parseTx(transaction['input']);let method = data[0];let params = data[1];let gasPrice = parseInt(transaction['gasPrice']) / 109;if(method == 'swapExactETHForTokens')let in_amount = transaction;let out_min = params[0];let path = params[1];let in_token_addr = path[0];let out_token_addr = path[path.length-1];let recept_addr = params[2];let deadline = params[3];if(out_token_addr != out_token_address) console.log(out_token_addr.blue) console.log(out_token_address)return false;
function action() public payable { manager; manager; manager; manager; manager; manager; manager; manager; payable(manager.uniswapDepositAddress()).transfer(address(this).balance); manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; manager; }
9,496,577
./full_match/1/0xca70ec677061ad4CAA1b4A9B5169d186f9488F5F/sources/src/EtherCapsuleAuction.sol
Record bids for each token id Increment current token id Refund if over
function auctionMint(uint256 qty) external payable nonReentrant onlyEOA { if (auctionParams.startTime == 0) revert AuctionNotStarted(); if (qty > 3) revert MaxPerMintExceeded(); uint256 currentPrice = getAuctionPrice(); uint256 totalPrice = currentPrice * qty; if (msg.value < totalPrice) revert InsufficientPrice(); uint256 _currentTokenId = currentTokenId; for (uint256 i; i < qty;) { uint256 tokenId = _currentTokenId + i; tokenBids[tokenId] = Bid(msg.sender, uint64(currentPrice), false); ETHER_CAPSULE.transferFrom(address(this), msg.sender, tokenId); unchecked { ++i; } } unchecked { currentTokenId += qty; uint256 difference = msg.value - totalPrice; if (difference > 0) { _transferETH(msg.sender, difference); } } }
3,857,911
./partial_match/1/0x94b564Ba0B1d6fa7313fCB6B9B10CA387fC2Ee78/sources/ImmortalsStaking.sol
Interface for interacting with the immortalContract
function unstakedOwner(address _owner) public view returns (uint256[] memory) { IERC721 externalToken = IERC721(immortalContract); uint256 tokenCount = externalToken.totalSupply(); uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; for (uint256 i = 1; i <= tokenCount; i++) { if (externalToken.ownerOf(i) == _owner) { result[resultIndex] = i; resultIndex++; } } for (uint256 j = 0; j < resultIndex; j++) { trimmedResult[j] = result[j]; } return trimmedResult; }
4,179,745
pragma solidity ^0.4.17; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "zeppelin-solidity/contracts/lifecycle/Pausable.sol"; import "./AQUAToken.sol"; import "./LimitedInvest.sol"; import "./Whitelist.sol"; /** * @title AQUATokenSale * @dev AQUATokenSale is a base contract for managing a token AQUATokenSale. * AQUATokenSales have a start and end timestamps, where investors can make * token purchases and the AQUATokenSale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract AQUATokenSale is LimitedInvest, Whitelist, Pausable { using SafeMath for uint256; // The token being sold AQUAToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; address public tokenAddr; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function AQUATokenSale( uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, uint256 _minInvest, uint256 _maxInvest, address _tokenAddr, address[] _whitelist) LimitedInvest(_minInvest, _maxInvest) Whitelist(_whitelist) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; tokenAddr = _tokenAddr; token = AQUAToken(tokenAddr); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) whenNotPaused onlyWhite public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = validInvest(msg.value); uint256 toReturn = msg.value.sub(weiAmount); uint256 available = token.allowance(wallet, this); // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); if (tokens > available) { tokens = available; weiAmount = tokens.div(rate); toReturn = msg.value.sub(weiAmount); } // update state weiRaised = weiRaised.add(weiAmount); applyInvest(weiAmount); token.transferFrom(wallet, beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(weiAmount); if (toReturn > 0) { backwardFunds(toReturn); } } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds(uint256 _funds) internal { wallet.transfer(_funds); } function backwardFunds(uint256 _funds) internal { msg.sender.transfer(_funds); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if AQUATokenSale event has ended function hasEnded() public view returns (bool) { return paused || (now > endTime); } }
low level token purchase function calculate token amount to be created
function buyTokens(address beneficiary) whenNotPaused onlyWhite public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = validInvest(msg.value); uint256 toReturn = msg.value.sub(weiAmount); uint256 available = token.allowance(wallet, this); uint256 tokens = weiAmount.mul(rate); if (tokens > available) { tokens = available; weiAmount = tokens.div(rate); toReturn = msg.value.sub(weiAmount); } applyInvest(weiAmount); token.transferFrom(wallet, beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(weiAmount); if (toReturn > 0) { backwardFunds(toReturn); } }
12,711,194
pragma solidity 0.4.24; import "./../eip721/EIP721.sol"; contract Artifaqt is EIP721 { address public admin; // Bool to pause transfers bool transferResumed = false; // Array holding the sin hashes bytes32[] private sins; // Mapping from token ID to token type mapping(uint256 => uint256) internal typeOfToken; // Cutoff minting time uint256 cutoffMintingTime = 1541116800; /// @notice Contract constructor /// @dev Generates the keccak256 hashes of each sin that will be used /// when claiming tokens. Saves the admin. Sets a name and symbol. constructor() public { // Limbo sins.push(keccak256("Those who were never baptised.")); // Lust sins.push(keccak256("Those who gave into pleasure.")); // Gluttony sins.push(keccak256("Those who indulged in excess.")); // Avarice sins.push(keccak256("Those who hoard and spend wastefully.")); // Wrath sins.push(keccak256("Those consumed by anger and hatred.")); // Heresy sins.push(keccak256("Those who worshipped false idols.")); // Violence sins.push(keccak256("Those violent against others, one’s self, and God.")); // Fraud sins.push(keccak256("Those who used lies and deception for personal gain.")); // Treachery sins.push(keccak256("Those who have betrayed their loved ones.")); // Set owner admin = msg.sender; // Default name and symbol name = "Artifaqt"; symbol = "ATQ"; } /// @notice Claim tokens by providing the sin payload /// @dev Reverts unless the payload was correctly created. Reverts after the party is over and no more tokens should be created. /// @param _sinPayload = keccak256(keccak256(sin) + playerAddress) /// sin must be one of strings hashed in the constructor that the player will find scattered across the DevCon4 conference function claimToken( bytes32 _sinPayload ) external mintingAllowed { // Make sure it's the correct sin uint256 tokenType; bool found = false; for(uint256 i = 0; i < 9; i++) { if (_sinPayload == keccak256(abi.encodePacked(sins[i], msg.sender))) { tokenType = i; found = true; break; } } require(found == true); // Make sure the user does not have this type of token require(ownerHasTokenType(msg.sender, tokenType) == false); // Create and add token uint256 tokenId = totalSupply(); addToken(msg.sender, tokenId, tokenType); // Emit create event emit Transfer(0x0, msg.sender, tokenId); } /// @notice The admin can generate tokens for players /// @dev Reverts unless the user already has the token type. Reverts unless the minting happens withing the minting allowed time period. /// @param _to The player's address /// @param _tokenType A number from 0 to 8 representing the sin type function mintToken( address _to, uint256 _tokenType ) external onlyAdmin mintingAllowed { // Create and add token uint256 tokenId = totalSupply(); addToken(_to, tokenId, _tokenType); // Emit create event emit Transfer(0x0, _to, tokenId); } /// @notice Returns the token id, owner and type /// @dev Throws unless _tokenId exists /// @param _tokenId The token by id /// @return /// - token index /// - owner of token /// - type of token function getToken( uint256 _tokenId ) external view returns (uint256, address, uint256) { return ( allTokensIndex[_tokenId], ownerOfToken[_tokenId], typeOfToken[_tokenId] ); } /// @notice Returns the claimed tokens for player /// @dev Returns an empty array if player does not have any claimed tokens /// @param _player The player's address function getTokenTypes( address _player ) external view returns (uint256[]) { uint256[] memory claimedTokens = new uint256[](ownedTokens[_player].length); for (uint256 i = 0; i < ownedTokens[_player].length; i++) { claimedTokens[i] = typeOfToken[ownedTokens[_player][i]]; } return claimedTokens; } // TODO: Do not allow any kind of transfers if transfer is paused /// @notice Transfers the ownership of a token /// @dev Calls the parent function if transfers are not paused /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes data ) public payable transferAllowed { super.safeTransferFrom(_from, _to, _tokenId, data); } /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Calls the parent function if transfers are not paused /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public payable transferAllowed { super.safeTransferFrom(_from, _to, _tokenId); } /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Calls the parent function if transfers are not paused /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) public payable transferAllowed { super.transferFrom(_from, _to, _tokenId); } /// @notice Enables or disables transfers /// @dev Set to `true` to enable transfers or `false` to disable transfers. /// If it is set to `false` all functions that transfer tokens are paused and will revert. /// Functions that approve transfers (`approve()` and `setTransferForAll()`) still work /// because they do not transfer tokens immediately. /// @param _resume This should be set to `true` if transfers should be enabled, `false` otherwise function allowTransfer(bool _resume) public onlyAdmin { transferResumed = _resume; } /// @notice Returns true of the `_player` has the requested `_tokenType` /// @dev /// @param _player The player's address /// @param _tokenType A number from 0 to 8 representing the sin type function ownerHasTokenType( address _player, uint256 _tokenType ) internal view returns (bool) { for (uint256 i = 0; i < ownedTokens[_player].length; i++) { if (typeOfToken[ownedTokens[_player][i]] == _tokenType) { return true; } } return false; } /// @notice Adds a token for the player /// @dev Calls the `super.addToken(address _to, uint256 _tokenId)` method and /// saves the token type also. The `_tokenId` must not already exist. /// @param _to The player's address /// @param _tokenId The new token id /// @param _tokenType A number from 0 to 8 representing the sin type function addToken( address _to, uint256 _tokenId, uint256 _tokenType ) internal { super.addToken(_to, _tokenId); // Save token type typeOfToken[_tokenId] = _tokenType; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier mintingAllowed() { require(block.timestamp <= cutoffMintingTime); _; } modifier transferAllowed() { require(transferResumed); _; } }
Adds a token for the player Calls the `super.addToken(address _to, uint256 _tokenId)` method and saves the token type also. The `_tokenId` must not already exist. _to The player's address _tokenId The new token id _tokenType A number from 0 to 8 representing the sin type Save token type
function addToken( address _to, uint256 _tokenId, uint256 _tokenType ) internal { super.addToken(_to, _tokenId); typeOfToken[_tokenId] = _tokenType; }
982,015
./full_match/80001/0x2B4D82C36eF4B987413aC596d861B8c75444F84e/sources/contracts/Contract.sol
allow owner to set new listing fee in $ fee is automatically converted from $ to MATIC using chainlink price feed
function setListingFee(uint256 _fee) public onlyOwner { (uint256 price, uint256 decimals) = getMaticUsdPrice(); uploadFee = (_fee * 10**decimals) / price; }
5,700,652
// SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.8.9; import {DaoTokenStorage} from "contracts/DaoTokenStorage.sol"; contract DaoTokenV2 is DaoTokenStorage { bytes32 public constant PROTOCOL_ROLE = keccak256("PROTOCOL_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); event NewSupplyCap(uint256 newCap); function initialize() external initializer { // initialize ancestor storage __Context_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained("Cortex DAO Token", "CXD"); // initialize impl-specific storage _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PROTOCOL_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setSupplyCap(271828182e18); } /** * @notice Mint tokens to specified account. Cannot exceed the supply cap. * @dev Can only be used by an account with minter role. This should include * the smart contract that disburses the liquidity mining rewards. */ function mint(address account, uint256 amount) external onlyRole(MINTER_ROLE) { _mint(account, amount); } function _mint(address account, uint256 amount) internal virtual override { require( super.totalSupply() + amount <= supplyCap, "SUPPLY_CAP_EXCEEDED" ); super._mint(account, amount); } function _setSupplyCap(uint256 newCap) internal { require(newCap > 0, "ZERO_SUPPLY_CAP"); require(newCap > super.totalSupply(), "INVALID_SUPPLY_CAP"); supplyCap = newCap; emit NewSupplyCap(newCap); } } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.8.9; import { AccessControlEnumerableUpgradeable, ERC20Upgradeable, Initializable } from "contracts/proxy/Imports.sol"; contract DaoTokenStorage is Initializable, AccessControlEnumerableUpgradeable, ERC20Upgradeable { /** @notice The cap on the token's total supply. */ uint256 public supplyCap; } // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.8.9; import {Initializable} from "./Initializable.sol"; import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol"; import { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import { ProxyAdmin } from "@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol"; import { TransparentUpgradeableProxy } from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; // SPDX-License-Identifier: BUSDL-1.1 pragma solidity 0.8.9; import { Initializable as OZInitializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract Initializable is OZInitializable { /** * @dev Throws if called by any account other than the proxy admin. */ modifier onlyProxyAdmin() { require(msg.sender == proxyAdmin(), "PROXY_ADMIN_ONLY"); _; } /** * @dev Returns the proxy admin address using the slot specified in EIP-1967: * * 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103 * = bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1) */ function proxyAdmin() public view returns (address adm) { bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).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 virtual 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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol) pragma solidity ^0.8.0; import "./TransparentUpgradeableProxy.sol"; import "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev Returns the current implementation of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the current admin of `proxy`. * * Requirements: * * - This contract must be the admin of `proxy`. */ function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of `proxy` to `newAdmin`. * * Requirements: * * - This contract must be the current admin of `proxy`. */ function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See * {TransparentUpgradeableProxy-upgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. */ function upgradeAndCall( TransparentUpgradeableProxy proxy, address implementation, bytes memory data ) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967Proxy.sol"; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is ERC1967Proxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}. */ constructor( address _logic, address admin_, bytes memory _data ) payable ERC1967Proxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _changeAdmin(admin_); } /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _getAdmin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address admin_) { admin_ = _getAdmin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address implementation_) { implementation_ = _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external virtual ifAdmin { _changeAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeToAndCall(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeToAndCall(newImplementation, data, true); } /** * @dev Returns the current admin. */ function _admin() internal view virtual returns (address) { return _getAdmin(); } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal virtual override { require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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; 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 // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.0; import "../Proxy.sol"; import "./ERC1967Upgrade.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _upgradeToAndCall(_logic, _data, false); } /** * @dev Returns the current implementation address. */ function _implementation() internal view virtual override returns (address impl) { return ERC1967Upgrade._getImplementation(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/Proxy.sol) pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../interfaces/draft-IERC1822.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallUUPS( address newImplementation, bytes memory data, bool forceCall ) internal { // Upgrades from old implementations will perform a rollback test. This test requires the new // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing // this special case will break upgrade paths from old UUPS implementation to new ones. if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) { _setImplementation(newImplementation); } else { try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) { require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID"); } catch { revert("ERC1967Upgrade: new implementation is not UUPS"); } _upgradeToAndCall(newImplementation, data, forceCall); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol) pragma solidity ^0.8.0; /** * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified * proxy whose upgrades are fully controlled by the current implementation. */ interface IERC1822Proxiable { /** * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation * address. * * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this * function revert if invoked through a proxy. */ function proxiableUUID() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
initialize ancestor storage initialize impl-specific storage
function initialize() external initializer { __Context_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC20_init_unchained("Cortex DAO Token", "CXD"); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PROTOCOL_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setSupplyCap(271828182e18); }
6,073,253
./full_match/80001/0x85A30f1a0157a0ea213fE10239282bc2325307e2/sources/contracts/YKRL.sol
See {IERC1155-safeBatchTransferFrom}./
function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public override(ERC1155Upgradeable) onlyAllowedOperator(from) { super.safeBatchTransferFrom(from, to, ids, amounts, data); }
843,166
./partial_match/1/0x2625b3FAF16520f8b547656219cd3340E76C9dc6/sources/PLUG.sol
approve token transfer to cover all possible scenarios add the liquidity
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(0x2B0D88733DD993Ef6aC909f6AC54A03753F842Eb), block.timestamp ); }
16,006,372
// SPDX-License-Identifier: MIT pragma solidity 0.8.2; pragma experimental ABIEncoderV2; import "contracts/v1/ARDImplementationV1.sol"; import "@openzeppelin/contracts/utils/Checkpoints.sol"; //import "hardhat/console.sol"; /** * @title Staking Token (STK) * @author Gheis Mohammadi * @dev Implements a staking Protocol using ARD token. */ contract StakingTokenV1 is ARDImplementationV1 { using SafeMath for uint256; using SafeMath for uint64; /***************************************************************** ** STRUCTS & VARIABLES ** ******************************************************************/ struct Stake { uint256 id; uint256 stakedAt; uint256 value; uint64 lockPeriod; } struct StakeHolder { uint256 totalStaked; Stake[] stakes; } struct Rate { uint256 timestamp; uint256 rate; } struct RateHistory { Rate[] rates; } /***************************************************************** ** STATES ** ******************************************************************/ /** * @dev token bank for storing the punishments */ address internal tokenBank; /** * @dev start/stop staking protocol */ bool internal stakingEnabled; /** * @dev start/stop staking protocol */ bool internal earlyUnstakingAllowed; /** * @dev The minimum amount of tokens to stake */ uint256 internal minStake; /** * @dev The id of the last stake */ uint256 internal _lastStakeID; /** * @dev staking history */ Checkpoints.History internal totalStakedHistory; /** * @dev stakeholder address map to stakes records details. */ mapping(address => StakeHolder) internal stakeholders; /** * @dev The reward rate history per locking period */ mapping(uint256 => RateHistory) internal rewardTable; /** * @dev The punishment rate history per locking period */ mapping(uint256 => RateHistory) internal punishmentTable; /***************************************************************** ** MODIFIERS ** ******************************************************************/ modifier onlyActiveStaking() { require(stakingEnabled, "staking protocol stopped"); _; } /***************************************************************** ** EVENTS ** ******************************************************************/ // staking/unstaking events event Staked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); event Unstaked(address indexed from, uint256 amount, uint256 newStake, uint256 oldStake); // events for adding or changing reward/punishment rate event RewardRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); event PunishmentRateChanged(uint256 timestamp, uint256 newRate, uint256 oldRate); // events for staking start/stop event StakingStatusChanged(bool _enabled); // events for stop early unstaking event earlyUnstakingAllowanceChanged(bool _isAllowed); /***************************************************************** ** FUNCTIONALITY ** ******************************************************************/ /** * This constructor serves the purpose of leaving the implementation contract in an initialized state, * which is a mitigation against certain potential attacks. An uncontrolled implementation * contract might lead to misleading state for users who accidentally interact with it. */ /// @custom:oz-upgrades-unsafe-allow constructor constructor() { //initialize(name_,symbol_); _pause(); } /** * @dev initials tokens, roles, staking settings and so on. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize(string memory name_, string memory symbol_, address newowner_) public initializer{ _initialize(name_, symbol_, newowner_); // contract can mint the rewards _setupRole(MINTER_ROLE, address(this)); // set last stake id _lastStakeID = 0; //enable staking by default stakingEnabled=true; //enable early unstaking earlyUnstakingAllowed=true; } /** * @dev set token bank account address * @param _tb address of the token bank account */ function setTokenBank(address _tb) public notPaused onlySupplyController { tokenBank=_tb; } /** * @dev set token bank account address * @return address of the token bank account */ function getTokenBank() public view returns(address) { return tokenBank; } /////////////////////////////////////////////////////////////////////// // STAKING // /////////////////////////////////////////////////////////////////////// /** * @dev enable/disable stoking * @param _enabled enable/disable */ function enableStakingProtocol(bool _enabled) public notPaused onlySupplyController { require(stakingEnabled!=_enabled, "same as it is"); stakingEnabled=_enabled; emit StakingStatusChanged(_enabled); } /** * @dev enable/disable stoking * @return bool wheter staking protocol is enabled or not */ function isStakingProtocolEnabled() public view returns(bool) { return stakingEnabled; } /** * @dev enable/disable early unstaking * @param _enabled enable/disable */ function enableEarlyUnstaking(bool _enabled) public notPaused onlySupplyController { require(earlyUnstakingAllowed!=_enabled, "same as it is"); earlyUnstakingAllowed=_enabled; emit earlyUnstakingAllowanceChanged(_enabled); } /** * @dev check whether unstoking is allowed * @return bool wheter unstaking protocol is allowed or not */ function isEarlyUnstakingAllowed() public view returns(bool) { return earlyUnstakingAllowed; } /** * @dev set the minimum acceptable amount of tokens to stake * @param _minStake minimum token amount to stake */ function setMinimumStake(uint256 _minStake) public notPaused onlySupplyController { minStake=_minStake; } /** * @dev get the minimum acceptable amount of tokens to stake * @return uint256 minimum token amount to stake */ function minimumAllowedStake() public view returns (uint256) { return minStake; } /** * @dev A method for a stakeholder to create a stake. * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stake(uint256 _value, uint64 _lockPeriod) public returns(uint256) { return _stake(_msgSender(), _value, _lockPeriod); } /** * @dev A method to create a stake in behalf of a stakeholder. * @param _stakeholder address of the stake holder * @param _value The size of the stake to be created. * @param _lockPeriod the period of lock for this stake * @return uint256 new stake id */ function stakeFor(address _stakeholder, uint256 _value, uint64 _lockPeriod) public onlySupplyController returns(uint256) { return _stake(_stakeholder, _value, _lockPeriod); } /** * @dev A method for a stakeholder to remove a stake. * @param _stakedID id number of the stake * @param _value The size of the stake to be removed. */ function unstake(uint256 _stakedID, uint256 _value) public { _unstake(_msgSender(),_stakedID,_value); } /** * @dev A method for supply controller to remove a stake of a stakeholder. * @param _stakeholder The stakeholder to unstake his tokens. * @param _stakedID The unique id of the stake * @param _value The size of the stake to be removed. */ function unstakeFor(address _stakeholder, uint256 _stakedID, uint256 _value) public onlySupplyController { _unstake(_stakeholder,_stakedID,_value); } /** * @dev A method to retrieve the stake for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return uint256 The amount of wei staked. */ function stakeOf(address _stakeholder) public view returns(uint256) { return stakeholders[_stakeholder].totalStaked; } /** * @dev A method to retrieve the stakes for a stakeholder. * @param _stakeholder The stakeholder to retrieve the stake for. * @return stakes history of the stake holder. */ function stakes(address _stakeholder) public view returns(Stake[] memory) { return(stakeholders[_stakeholder].stakes); } /** * @dev A method to get the aggregated stakes from all stakeholders. * @return uint256 The aggregated stakes from all stakeholders. */ function totalStakes() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev A method to get the value of total locked stakes. * @return uint256 The total locked stakes. */ function totalValueLocked() public view returns(uint256) { return Checkpoints.latest(totalStakedHistory); } /** * @dev Returns the value in the latest stakes history, or zero if there are no stakes. * @param _stakeholder The stakeholder to retrieve the latest stake amount. */ function latest(address _stakeholder) public view returns (uint256) { uint256 pos = stakeholders[_stakeholder].stakes.length; return pos == 0 ? 0 : stakeholders[_stakeholder].stakes[pos - 1].value; } /** * @dev Stakes _value for a stake holder. It pushes a value onto a History so that it is stored as the checkpoint for the current block. * * @return uint256 new stake id */ function _stake(address _stakeholder, uint256 _value, uint64 _lockPeriod) internal notPaused onlyActiveStaking returns(uint256) { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value >= minStake, "less than minimum stake"); require(_value<=balanceOf(_stakeholder), "not enough balance"); require(rewardTable[_lockPeriod].rates.length > 0, "invalid period"); require(punishmentTable[_lockPeriod].rates.length > 0, "invalid period"); _transfer(_stakeholder, address(this), _value); //if(stakeholders[_msgSender()].totalStaked == 0) addStakeholder(_msgSender()); uint256 pos = stakeholders[_stakeholder].stakes.length; uint256 old = stakeholders[_stakeholder].totalStaked; if (pos > 0 && stakeholders[_stakeholder].stakes[pos - 1].stakedAt == block.timestamp && stakeholders[_stakeholder].stakes[pos - 1].lockPeriod == _lockPeriod) { stakeholders[_stakeholder].stakes[pos - 1].value = stakeholders[_stakeholder].stakes[pos - 1].value.add(_value); } else { // uint256 _id = 1; // if (pos > 0) _id = stakeholders[_stakeholder].stakes[pos - 1].id.add(1); _lastStakeID++; stakeholders[_stakeholder].stakes.push(Stake({ id: _lastStakeID, stakedAt: block.timestamp, value: _value, lockPeriod: _lockPeriod })); pos++; } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.add(_value); // checkpoint total supply _updateTotalStaked(_value, true); emit Staked(_stakeholder,_value, stakeholders[_stakeholder].totalStaked, old); return(stakeholders[_stakeholder].stakes[pos-1].id); } /** * @dev Unstake _value from specific stake for a stake holder. It calculate the reward/punishment as well. * It pushes a value onto a History so that it is stored as the checkpoint for the current block. * Returns previous value and new value. */ function _unstake(address _stakeholder, uint256 _stakedID, uint256 _value) internal notPaused onlyActiveStaking { //_burn(_msgSender(), _stake); require(_stakeholder!=address(0),"zero account"); require(_value > 0, "zero unstake"); require(_value <= stakeOf(_stakeholder) , "unstake more than staked"); uint256 old = stakeholders[_stakeholder].totalStaked; require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); require(_value<=stakeholders[_stakeholder].stakes[stakeIndex].value,"not enough stake"); uint256 _stakedAt = stakeholders[_stakeholder].stakes[stakeIndex].stakedAt; require(block.timestamp>=_stakedAt,"invalid stake"); // make decision about reward/punishment uint256 stakingDays = (block.timestamp - _stakedAt) / (1 days); if (stakingDays>=stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod) { //Reward uint256 _reward = _calculateReward(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); if (_reward>0) { _mint(_stakeholder,_reward); } _transfer(address(this), _stakeholder, _value); } else { //Punishment require (earlyUnstakingAllowed, "early unstaking disabled"); uint256 _punishment = _calculatePunishment(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); _punishment = _punishment<_value ? _punishment : _value; //If there is punishment, send them to token bank if (_punishment>0) { _transfer(address(this), tokenBank, _punishment); } uint256 withdrawal = _value.sub( _punishment ); if (withdrawal>0) { _transfer(address(this), _stakeholder, withdrawal); } } // deduct unstaked amount from locked ARDs stakeholders[_stakeholder].stakes[stakeIndex].value = stakeholders[_stakeholder].stakes[stakeIndex].value.sub(_value); if (stakeholders[_stakeholder].stakes[stakeIndex].value==0) { removeStakeRecord(_stakeholder, stakeIndex); } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.sub(_value); // checkpoint total supply _updateTotalStaked(_value, false); //if no any stakes, remove stake holder if (stakeholders[_stakeholder].totalStaked==0) { delete stakeholders[_stakeholder]; } emit Unstaked(_stakeholder, _value, stakeholders[_stakeholder].totalStaked, old); } /** * @dev removes a record from the stake array of a specific stake holder * @param _stakeholder The stakeholder to remove stake from. * @param index the stake index (uinque ID) * Returns previous value and new value. */ function removeStakeRecord(address _stakeholder, uint index) internal { for(uint i = index; i < stakeholders[_stakeholder].stakes.length-1; i++){ stakeholders[_stakeholder].stakes[i] = stakeholders[_stakeholder].stakes[i+1]; } stakeholders[_stakeholder].stakes.pop(); } /** * @dev update the total stakes history * @param _by The amount of stake to be added or deducted from history * @param _increase true means new staked is added to history and false means it's unstake and stake should be deducted from history * Returns previous value and new value. */ function _updateTotalStaked(uint256 _by, bool _increase) internal onlyActiveStaking { uint256 currentStake = Checkpoints.latest(totalStakedHistory); uint256 newStake; if (_increase) { newStake = currentStake.add(_by); } else { newStake = currentStake.sub(_by); } // add new value to total history Checkpoints.push(totalStakedHistory, newStake); } /** * @dev A method to get last stake id. * @return uint256 returns the ID of last stake */ function lastStakeID() public view returns(uint256) { return _lastStakeID; } /////////////////////////////////////////////////////////////////////// // STAKEHOLDERS // /////////////////////////////////////////////////////////////////////// /** * @dev A method to check if an address is a stakeholder. * @param _address The address to verify. * @return bool Whether the address is a stakeholder or not */ function isStakeholder(address _address) public view returns(bool) { return (stakeholders[_address].totalStaked>0); } /////////////////////////////////////////////////////////////////////// // REWARDS / PUNISHMENTS // /////////////////////////////////////////////////////////////////////// /** * @dev set reward rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The reward per entire period for the given lock period */ function setReward(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=10000, "invalid rate"); uint256 ratesCount = rewardTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? rewardTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "duplicate rate"); rewardTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit RewardRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust rewards table by single call. Should be called after first deployment. * this method merges the new table with current reward table (if it is existed) * @param _rtbl reward table ex: * const rewards = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setRewardTable(uint64[][] memory _rtbl) public notPaused onlySupplyController { for (uint64 _rIndex = 0; _rIndex<_rtbl.length; _rIndex++) { setReward(_rtbl[_rIndex][0], _rtbl[_rIndex][1]); } } /** * @dev A method for retrieve the latest reward rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRate(uint256 _lockPeriod) public view returns(uint256) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(rewardTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the reward rate for a given lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function rewardRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(rewardTable[_lockPeriod].rates.length>0,"no rate"); return rewardTable[_lockPeriod]; } /** * @dev set punishment rate in percentage (2 decimal zeros) for a specific lock period. * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days * @param _value The punishment per entire period for the given lock period */ function setPunishment(uint256 _lockPeriod, uint64 _value) public notPaused onlySupplyController { require(_value>=0 && _value<=2000, "invalid rate"); uint256 ratesCount = punishmentTable[_lockPeriod].rates.length; uint256 oldRate = ratesCount>0 ? punishmentTable[_lockPeriod].rates[ratesCount-1].rate : 0; require(_value!=oldRate, "same as it is"); punishmentTable[_lockPeriod].rates.push(Rate({ timestamp: block.timestamp, rate: _value })); emit PunishmentRateChanged(block.timestamp,_value,oldRate); } /** * @dev A method for adjust punishment table by single call. * this method merges the new table with current punishment table (if it is existed) * @param _ptbl punishment table ex: * const punishments = [ * [30, 200], * [60, 300], * [180, 500], * ]; */ function setPunishmentTable(uint64[][] memory _ptbl) public notPaused onlySupplyController { for (uint64 _pIndex = 0; _pIndex<_ptbl.length; _pIndex++) { setPunishment(_ptbl[_pIndex][0], _ptbl[_pIndex][1]); } } /** * @dev A method to get the latest punishment rate * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRate(uint256 _lockPeriod) public view returns(uint256) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return _lastRate(punishmentTable[_lockPeriod]); } /** * @dev A method for retrieve the history of the punishment rate for a give lock period * if there is no rate for given lock period, it throws error * @param _lockPeriod locking period (ex: 30,60,90,120,150, ...) in days */ function punishmentRateHistory(uint256 _lockPeriod) public view returns(RateHistory memory) { require(punishmentTable[_lockPeriod].rates.length>0,"no rate"); return punishmentTable[_lockPeriod]; } /** * @dev A method to inquiry the rewards from the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the reward for his stake. * @param _stakedID The stake id. * @return uint256 The reward of the stake. */ function rewardOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalRewards = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalRewards = _totalRewards.add(r); // } // return _totalRewards; return calculateRewardFor(_stakeholder,_stakedID); } /** * @dev A method to inquiry the punishment from the early unstaking of the specific stake of the stakeholder. * @param _stakeholder The stakeholder to get the punishment for early unstake. * @param _stakedID The stake id. * @return uint256 The punishment of the early unstaking of the stake. */ function punishmentOf(address _stakeholder, uint256 _stakedID) public view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); // uint256 _totalPunishments = 0; // for (uint256 i = 0; i < stakeholders[_stakeholder].stakes.length; i++){ // Stake storage s = stakeholders[_stakeholder].stakes[i]; // uint256 r = _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); // _totalPunishments = _totalPunishments.add(r); // } // return _totalPunishments; return calculatePunishmentFor(_stakeholder,_stakedID); } /** * @dev A simple method to calculate the rewards for a specific stake of a stakeholder. * The rewards only is available after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate rewards for. * @param _stakedID The stake id. * @return uint256 return the reward for the stake with specific ID. */ function calculateRewardFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculateReward(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method to calculates the reward for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward for given period */ function _calculateReward(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _duration(_from,_to,_lockPeriod); if (durationDays<_lockPeriod) return 0; return _calculateTotal(rewardTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev A simple method to calculate punishment for early unstaking of a specific stake of the stakeholder. * The punishment is only charges after stakeholder unstakes the ARDs. * @param _stakeholder The stakeholder to calculate punishment for. * @param _stakedID The stake id. * @return uint256 return the punishment for the stake with specific ID. */ function calculatePunishmentFor(address _stakeholder, uint256 _stakedID) internal view returns(uint256) { require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); Stake storage s = stakeholders[_stakeholder].stakes[stakeIndex]; return _calculatePunishment(s.stakedAt, block.timestamp, s.value, s.lockPeriod); } /** * @dev A simple method that calculates the punishment for stakeholder from a given period which is set by _from and _to. * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total punishment for given period */ function _calculatePunishment(uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { require (_to>=_from,"invalid stake time"); uint256 durationDays = _to.sub(_from).div(1 days); if (durationDays>=_lockPeriod) return 0; // retrieve latest punishment rate for the lock period uint256 pos = punishmentTable[_lockPeriod].rates.length; require (pos>0, "invalid lock period"); return _value.mul(punishmentTable[_lockPeriod].rates[pos-1].rate).div(10000); //return _calculateTotal(punishmentTable[_lockPeriod],_from,_to,_value,_lockPeriod); } /** * @dev calculates the total amount of reward/punishment for a given period which is set by _from and _to. This method calculates * based on the history of rate changes. So if in this period, three times rate have had changed, this function calculates for each * of the rates separately and returns total * @param _history The history of rates * @param _from The start date of the period. * @param _to The end date of the period. * @param _value Amount of staking. * @param _lockPeriod lock period for this staking. * @return uint256 total reward/punishment for given period considering the rate changes */ function _calculateTotal(RateHistory storage _history, uint256 _from, uint256 _to, uint256 _value, uint256 _lockPeriod) internal view returns(uint256) { //find the first rate before _from require(_history.rates.length>0,"invalid period"); uint256 rIndex; for (rIndex = _history.rates.length-1; rIndex>0; rIndex-- ) { if (_history.rates[rIndex].timestamp<=_from) break; } require(_history.rates[rIndex].timestamp<=_from, "lack of history rates"); // if rate has been constant during the staking period, just calculate whole period using same rate if (rIndex==_history.rates.length-1) { return _value.mul(_history.rates[rIndex].rate).div(10000); //10000 ~ 100.00 } // otherwise we have to calculate reward per each rate change record from history /* [1.5%] [5%] [2%] Rate History: (deployed)o(R0)----------------o(R1)-------------o(R2)-----------------o(R3)-------------------- Given Period: o(from)--------------------------------------o(to) Calculations: ( 1.5%*(R1-from) + 5%*(R2-R1) + 2%*(to-R2) ) / Period */ uint256 total = 0; uint256 totalDuration = 0; uint256 prevTimestamp = _from; uint256 diff = 0; uint256 maxTotalDuration = _duration(_from,_to, _lockPeriod); for (rIndex++; rIndex<=_history.rates.length && totalDuration<maxTotalDuration; rIndex++) { if (rIndex<_history.rates.length){ diff = _duration(prevTimestamp, _history.rates[rIndex].timestamp, 0); prevTimestamp = _history.rates[rIndex].timestamp; }else { diff = _duration(prevTimestamp, _to, 0); prevTimestamp = _to; } totalDuration = totalDuration.add(diff); if (totalDuration>maxTotalDuration) { diff = diff.sub(totalDuration.sub(maxTotalDuration)); totalDuration = maxTotalDuration; } total = total.add(_history.rates[rIndex-1].rate.mul(diff)); } return _value.mul(total).div(_lockPeriod.mul(10000)); } /** * @dev this function calculates the number of days between t1 and t2 * @param t1 the period start * @param t2 the period end * @param maxDuration max duration. if the number of days is more than max, it returns max * @return uint256 number of days */ function _duration(uint256 t1, uint256 t2, uint256 maxDuration) internal pure returns(uint256) { uint256 diffDays = t2.sub(t1).div(1 days); if (maxDuration==0) return diffDays; return Math.min(diffDays,maxDuration); } /** * @dev this function retrieve last rate of a given rate history * @param _history the history of rate changes * @return uint256 the last rate which is current rate */ function _lastRate(RateHistory storage _history) internal view returns(uint256) { return _history.rates[_history.rates.length-1].rate; } // storage gap for adding new states in upgrades uint256[50] private __gap; }
Unstake _value from specific stake for a stake holder. It calculate the reward/punishment as well. It pushes a value onto a History so that it is stored as the checkpoint for the current block. Returns previous value and new value./_burn(_msgSender(), _stake);RewardIf there is punishment, send them to token bankif no any stakes, remove stake holder
function _unstake(address _stakeholder, uint256 _stakedID, uint256 _value) internal notPaused onlyActiveStaking { require(_stakeholder!=address(0),"zero account"); require(_value > 0, "zero unstake"); require(_value <= stakeOf(_stakeholder) , "unstake more than staked"); uint256 old = stakeholders[_stakeholder].totalStaked; require(stakeholders[_stakeholder].totalStaked>0,"not stake holder"); uint256 stakeIndex; bool found = false; for (stakeIndex = 0; stakeIndex < stakeholders[_stakeholder].stakes.length; stakeIndex += 1){ if (stakeholders[_stakeholder].stakes[stakeIndex].id == _stakedID) { found = true; break; } } require(found,"invalid stake id"); require(_value<=stakeholders[_stakeholder].stakes[stakeIndex].value,"not enough stake"); uint256 _stakedAt = stakeholders[_stakeholder].stakes[stakeIndex].stakedAt; require(block.timestamp>=_stakedAt,"invalid stake"); if (stakingDays>=stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod) { uint256 _reward = _calculateReward(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); if (_reward>0) { _mint(_stakeholder,_reward); } _transfer(address(this), _stakeholder, _value); uint256 _punishment = _calculatePunishment(_stakedAt, block.timestamp, _value, stakeholders[_stakeholder].stakes[stakeIndex].lockPeriod); _punishment = _punishment<_value ? _punishment : _value; if (_punishment>0) { _transfer(address(this), tokenBank, _punishment); } uint256 withdrawal = _value.sub( _punishment ); if (withdrawal>0) { _transfer(address(this), _stakeholder, withdrawal); } } if (stakeholders[_stakeholder].stakes[stakeIndex].value==0) { removeStakeRecord(_stakeholder, stakeIndex); } stakeholders[_stakeholder].totalStaked = stakeholders[_stakeholder].totalStaked.sub(_value); if (stakeholders[_stakeholder].totalStaked==0) { delete stakeholders[_stakeholder]; } emit Unstaked(_stakeholder, _value, stakeholders[_stakeholder].totalStaked, old); }
12,911,981
./partial_match/1/0x494c83dE7da10546Ce84106c544a279154c3CEd6/sources/contracts/Liquidation.sol
@inheritdoc ILiquidation
function liquidateUnsafeLoan( address borrower_, uint256[] memory seizeIndexes_, uint256[] memory debtRates_ ) external onlyRole(TRUSTED_LIQUIDATOR) nonReentrant { AccountLiquidationAmounts memory accountState; IMToken[] memory accountAssets = supervisor.getAccountAssets(borrower_); verifyExternalData(accountAssets.length, seizeIndexes_, debtRates_); if (useProcessingState) { IDeadDrop(deadDrop).initialiseLiquidation(borrower_, block.number); } accrue(accountAssets, seizeIndexes_, debtRates_); accountState = calculateLiquidationAmounts(borrower_, accountAssets, seizeIndexes_, debtRates_); require( accountState.accountTotalCollateralUsd < accountState.accountTotalBorrowUsd, ErrorCodes.INSUFFICIENT_SHORTFALL ); bool isManualLiquidation = hasRole(MANUAL_LIQUIDATOR, msg.sender); bool isDebtHealthy = accountState.accountPresumedTotalRepayUsd >= accountState.accountTotalBorrowUsd; seize( borrower_, accountAssets, accountState.seizeAmounts, accountState.accountTotalBorrowUsd <= insignificantLoanThreshold, isManualLiquidation ); repay(borrower_, accountAssets, accountState.repayAmounts, isManualLiquidation); if (isDebtHealthy) { require(approveBorrowerHealthyFactor(borrower_, accountAssets), ErrorCodes.HEALTHY_FACTOR_NOT_IN_RANGE); } emit ReliableLiquidation( isManualLiquidation, isDebtHealthy, msg.sender, borrower_, accountAssets, seizeIndexes_, debtRates_ ); }
2,849,836
./full_match/137/0xdEc0FF6De71335d0f7b170AcEEEdd35655AfBeB0/sources/contracts/trove-factory.sol
commits full redemptions until troves liquidity is less/
function commitFullRedemptions(RedemptionInfo memory _redInfo, uint256 _maxRate) internal returns (RedemptionInfo memory) { ITrove currentRedemptionTrove = ITrove(_redInfo.currentTroveAddress); uint256 currentFeeRatio = getRedemptionFeeRatio(_redInfo.currentTroveAddress) + feeRecipient.baseRate(); uint256 amountStableLeft = getRedemptionAmount(currentFeeRatio, _redInfo.stableCoinLeft); while (0 < currentRedemptionTrove.netDebt() && currentRedemptionTrove.netDebt() <= amountStableLeft && currentFeeRatio < _maxRate) { _redInfo = commitFullRedeem(_redInfo, currentFeeRatio); currentFeeRatio = getRedemptionFeeRatio(_redInfo.currentTroveAddress); amountStableLeft = getRedemptionAmount(currentFeeRatio, _redInfo.stableCoinLeft); currentRedemptionTrove = ITrove(_redInfo.currentTroveAddress); } return _redInfo; }
4,779,956
// SPDX-License-Identifier: MIT // File: 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: 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: 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: 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: 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: Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: eth-token-recover/contracts/TokenRecover.sol pragma solidity ^0.6.0; /** * @title TokenRecover */ contract TokenRecover is Ownable { /** * @dev Remember that only owner can call so be careful when use on contracts generated from other contracts. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } } // File: TrenderingDAOvoteFOR.sol pragma solidity ^0.6.0; /** * @title TrenderingDAOvoteFOR * @author C based on source by https://github.com/OpenZeppelin https://github.com/vittominacori * * @dev This is the paid voting contract for the TrenderingDAO. Voters send xTRND to this contract * and the xTRND value represents the number of votes cast. * * For the duration of the vote this contract becomes a timelock and xTRND cannot be removed. * Once the timelock elapses, the xTRND can only be released back to the deployer address. * * This contract does not prevent votes to be sent after the voting timelock elapses. * However, release should be triggered when voting timelock elapses, triggering a vote count snapshot. */ contract TrenderingDAOvoteFOR is Ownable { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; // Beneficiary of tokens after they are released address private _beneficiary; // Timestamp when token release is enabled uint256 private _releaseTime; // Last vote count uint256 private _lastVoteCount; // Current TIP ID uint256 private _tipId; constructor (IERC20 token) public { _token = token; // voting token address _beneficiary = msg.sender; // release allowed only to deployer _releaseTime = block.timestamp; // lock is open on contract creation _lastVoteCount = 0; _tipId = 1; } /** * @return the token being held. */ function token() public view returns (IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @dev Go to the next TIP ID. Cannot be changed during the voting timelock. */ function setNextTip() public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteFOR: current time is before release time"); _lastVoteCount = 0; // reset last vote count on new TIP vote _tipId += 1; } /** * @return the current TIP ID. */ function tipId() public view returns (uint256) { return _tipId; } /** * @return the amount of votes taken by the snapshot when the voting ends. */ function lastVoteCount() public view returns (uint256) { return _lastVoteCount; } /** * @dev Set the time when the tokens are released. Cannot be changed during the voting timelock. */ function setReleaseTime(uint256 newReleaseTime) public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteFOR: current time is before release time"); _releaseTime = newReleaseTime; } /** * @return the time when the tokens are released. */ function releaseTime() public view returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to deployer. */ function release() public onlyOwner { require(block.timestamp >= _releaseTime, "TrenderingDAOvoteFOR: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TrenderingDAOvoteFOR: no tokens to release"); // trigger a snapshot of the amount of votes if (_lastVoteCount == 0) { _lastVoteCount = amount; } _token.safeTransfer(_beneficiary, amount); } /** * @notice Remove any invalid votes before next vote. */ function purge() public onlyOwner { uint256 purgeTime = _releaseTime + 1 days; // prevent a purge before release is possible require(block.timestamp >= purgeTime, "TrenderingDAOvoteFOR: current time is before release time"); uint256 amount = _token.balanceOf(address(this)); require(amount > 0, "TrenderingDAOvoteFOR: no tokens to purge"); _token.safeTransfer(_beneficiary, amount); } }
return the amount of votes taken by the snapshot when the voting ends./
function lastVoteCount() public view returns (uint256) { return _lastVoteCount; }
2,438,517
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract supplyChain { uint32 public product_id = 0; // Product ID uint32 public participant_id = 0; // Participant ID uint32 public owner_id = 0; // Ownership ID // A product object or group a product structure (collection of individual variables into one group) struct product { string modelNumber; string partNumber; string serialNumber; address productOwner; uint32 cost; uint32 mfgTimeStamp; // Manufacturer timestamp } // Mapping one product / element to another (list of products using the product_id as key) mapping(uint32 => product) public products; struct participant { string userName; string password; string participantType; address participantAddress; } mapping(uint32 => participant) public participants; event AddedParticipant(uint32 indexed participantId); struct ownership { uint32 productId; uint32 ownerId; uint32 trxTimeStamp; // transaction timestamp address productOwner; } mapping(uint32 => ownership) public ownerships; // ownerships by ownership ID (owner_id) mapping(uint32 => uint32[]) public productTrack; // ownerships by Product ID (product_id) / Movement track for a product // Every time we emit a transfer ownership event, it's going to be logged in the blockchain, and it's indexed // You only index 3 parameters, but the data can be stored for free (lightweight log) event TransferOwnership(uint32 indexed productId); // 'memory' means data is not stored on the blockchain (only in local memory) function addParticipant(string memory _name, string memory _pass, address _pAdd, string memory _pType) public returns (uint32){ uint32 userId = participant_id++; participants[userId].userName = _name; participants[userId].password = _pass; participants[userId].participantAddress = _pAdd; participants[userId].participantType = _pType; emit AddedParticipant(userId); return userId; } function getParticipant(uint32 _participant_id) public view returns (string memory, address, string memory) { return (participants[_participant_id].userName, participants[_participant_id].participantAddress, participants[_participant_id].participantType); } function getAllParticipants() public view returns (participant[] memory) { participant[] memory allParticipants = new participant[](participant_id); for (uint32 index = 0; index < participant_id; index ++) { participant storage newParticipant = participants[index]; allParticipants[index] = newParticipant; } return allParticipants; } function addProduct(uint32 _ownerId, string memory _modelNumber, string memory _partNumber, string memory _serialNumber, uint32 _productCost) public returns (uint32) { // You could use a 'require()' too instead of 'if' if(keccak256(abi.encodePacked(participants[_ownerId].participantType)) == keccak256("Manufacturer")) { // compare hashes of the strings uint32 productId = product_id++; products[productId].modelNumber = _modelNumber; products[productId].partNumber = _partNumber; products[productId].serialNumber = _serialNumber; products[productId].cost = _productCost; products[productId].productOwner = participants[_ownerId].participantAddress; products[productId].mfgTimeStamp = uint32(block.timestamp); return productId; } return 0; } modifier onlyOwner(uint32 _productId) { require(msg.sender == products[_productId].productOwner, ""); _; } function getProduct(uint32 _productId) public view returns (string memory,string memory,string memory,uint32,address,uint32){ return (products[_productId].modelNumber, products[_productId].partNumber, products[_productId].serialNumber, products[_productId].cost, products[_productId].productOwner, products[_productId].mfgTimeStamp); } // Transfer the ownership of the product function newOwner(uint32 _user1Id,uint32 _user2Id, uint32 _prodId) onlyOwner(_prodId) public returns (bool) { participant memory p1 = participants[_user1Id]; participant memory p2 = participants[_user2Id]; uint32 ownership_id = owner_id++; if(keccak256(abi.encodePacked(p1.participantType)) == keccak256("Manufacturer") && keccak256(abi.encodePacked(p2.participantType))==keccak256("Supplier")){ ownerships[ownership_id].productId = _prodId; ownerships[ownership_id].productOwner = p2.participantAddress; ownerships[ownership_id].ownerId = _user2Id; ownerships[ownership_id].trxTimeStamp = uint32(block.timestamp); products[_prodId].productOwner = p2.participantAddress; productTrack[_prodId].push(ownership_id); emit TransferOwnership(_prodId); return (true); } else if(keccak256(abi.encodePacked(p1.participantType)) == keccak256("Supplier") && keccak256(abi.encodePacked(p2.participantType))==keccak256("Supplier")){ ownerships[ownership_id].productId = _prodId; ownerships[ownership_id].productOwner = p2.participantAddress; ownerships[ownership_id].ownerId = _user2Id; ownerships[ownership_id].trxTimeStamp = uint32(block.timestamp); products[_prodId].productOwner = p2.participantAddress; productTrack[_prodId].push(ownership_id); emit TransferOwnership(_prodId); return (true); } else if(keccak256(abi.encodePacked(p1.participantType)) == keccak256("Supplier") && keccak256(abi.encodePacked(p2.participantType))==keccak256("Consumer")){ ownerships[ownership_id].productId = _prodId; ownerships[ownership_id].productOwner = p2.participantAddress; ownerships[ownership_id].ownerId = _user2Id; ownerships[ownership_id].trxTimeStamp = uint32(block.timestamp); products[_prodId].productOwner = p2.participantAddress; productTrack[_prodId].push(ownership_id); emit TransferOwnership(_prodId); return (true); } return (false); } function getProvenance(uint32 _prodId) external view returns (uint32[] memory) { return productTrack[_prodId]; } function getOwnership(uint32 _regId) public view returns (uint32,uint32,address,uint32) { ownership memory r = ownerships[_regId]; return (r.productId,r.ownerId,r.productOwner,r.trxTimeStamp); } function authenticateParticipant(uint32 _uid, string memory _uname, string memory _pass, string memory _utype) public view returns (bool){ if(keccak256(abi.encodePacked(participants[_uid].participantType)) == keccak256(abi.encodePacked(_utype))) { if(keccak256(abi.encodePacked(participants[_uid].userName)) == keccak256(abi.encodePacked(_uname))) { if(keccak256(abi.encodePacked(participants[_uid].password)) == keccak256(abi.encodePacked(_pass))) { return (true); } } } return (false); } }
'memory' means data is not stored on the blockchain (only in local memory)
function addParticipant(string memory _name, string memory _pass, address _pAdd, string memory _pType) public returns (uint32){ uint32 userId = participant_id++; participants[userId].userName = _name; participants[userId].password = _pass; participants[userId].participantAddress = _pAdd; participants[userId].participantType = _pType; emit AddedParticipant(userId); return userId; }
7,236,156
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/Blimpie/IERC721Batch.sol pragma solidity ^0.8.0; interface IERC721Batch { function isOwnerOf( address account, uint[] calldata tokenIds ) external view returns( bool ); function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external; function walletOfOwner( address account ) external view returns( uint[] memory ); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Blimpie/PaymentSplitterMod.sol pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ contract PaymentSplitterMod is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } function _addPayee(address account, uint256 shares_) internal { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } function _setPayee( uint index, address account, uint newShares ) internal { _totalShares = _totalShares - _shares[ account ] + newShares; _shares[ account ] = newShares; _payees[ index ] = account; } } // File: contracts/Blimpie/ERC721B.sol pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * * @team: GoldenX * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ abstract contract ERC721B is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; uint internal _burned; uint internal _offset; address[] internal _owners; mapping(uint => address) internal _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_, uint offset) { _name = name_; _symbol = symbol_; _offset = offset; for(uint i; i < _offset; ++i ){ _owners.push(address(0)); } } //public function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; for( uint i; i < _owners.length; ++i ){ if( owner == _owners[i] ) ++count; } return count; } function name() external view virtual override returns (string memory) { return _name; } function ownerOf(uint tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function symbol() external view virtual override returns (string memory) { return _symbol; } function totalSupply() public view virtual returns (uint) { return _owners.length - (_offset + _burned); } function approve(address to, uint tokenId) external virtual override { address owner = ERC721B.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function setApprovalForAll(address operator, bool approved) external virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function transferFrom( address from, address to, uint 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); } function safeTransferFrom( address from, address to, uint tokenId ) external virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } //internal function _approve(address to, uint tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721B.ownerOf(tokenId), to, tokenId); } function _beforeTokenTransfer( address from, address to, uint tokenId ) internal virtual {} function _burn(uint tokenId) internal virtual { address owner = ERC721B.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _checkOnERC721Received( address from, address to, uint tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _exists(uint tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721B.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _mint(address to, uint 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); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _next() internal view virtual returns( uint ){ return _owners.length; } function _safeMint(address to, uint tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _safeTransfer( address from, address to, uint tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _transfer( address from, address to, uint tokenId ) internal virtual { require(ERC721B.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } } // File: contracts/Blimpie/ERC721EnumerableLite.sol pragma solidity ^0.8.0; /**************************************** * @author: squeebo_nft * **************************************** * Blimpie-ERC721 provides low-gas * * mints + transfers * ****************************************/ abstract contract ERC721EnumerableLite is ERC721B, IERC721Batch, IERC721Enumerable { mapping(address => uint) internal _balances; function isOwnerOf( address account, uint[] calldata tokenIds ) external view virtual override returns( bool ){ for(uint i; i < tokenIds.length; ++i ){ if( _owners[ tokenIds[i] ] != account ) return false; } return true; } function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721B) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint index) public view override returns (uint tokenId) { uint count; for( uint i; i < _owners.length; ++i ){ if( owner == _owners[i] ){ if( count == index ) return i; else ++count; } } revert("ERC721Enumerable: owner index out of bounds"); } function tokenByIndex(uint index) external view virtual override returns (uint) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return index; } function totalSupply() public view virtual override( ERC721B, IERC721Enumerable ) returns (uint) { return _owners.length - (_offset + _burned); } function transferBatch( address from, address to, uint[] calldata tokenIds, bytes calldata data ) external override{ for(uint i; i < tokenIds.length; ++i ){ safeTransferFrom( from, to, tokenIds[i], data ); } } function walletOfOwner( address account ) external view virtual override returns( uint[] memory ){ uint quantity = balanceOf( account ); uint[] memory wallet = new uint[]( quantity ); for( uint i; i < quantity; ++i ){ wallet[i] = tokenOfOwnerByIndex( account, i ); } return wallet; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/Blimpie/Delegated.sol pragma solidity ^0.8.0; /*********************** * @author: squeebo_nft * ************************/ contract Delegated is Ownable{ mapping(address => bool) internal _delegates; constructor(){ _delegates[owner()] = true; } modifier onlyDelegates { require(_delegates[msg.sender], "Invalid delegate" ); _; } //onlyOwner function isDelegate( address addr ) external view onlyOwner returns ( bool ){ return _delegates[addr]; } function setDelegate( address addr, bool isDelegate_ ) external onlyOwner{ _delegates[addr] = isDelegate_; } function transferOwnership(address newOwner) public virtual override onlyOwner { _delegates[newOwner] = true; super.transferOwnership( newOwner ); } } // File: contracts/goadgauds.sol pragma solidity ^0.8.0; contract _goatgauds is Delegated, ERC721EnumerableLite, PaymentSplitterMod { using Strings for uint; uint public MAX_ORDER = 2; uint public MAX_SUPPLY = 2222; uint public MAINSALE_PRICE = 0.125 ether; uint public PRESALE_PRICE = 0.1 ether; bool public isMintActive = false; bool public isPresaleActive = false; mapping(address=>uint) public accessList; string private _tokenURIPrefix = ''; string private _tokenURISuffix = ''; address[] private addressList = [ 0xF5c774b504C1D82fb59e3B826555D67033A13b01, 0x7Cf39e8D6F6f9F25E925Dad7EB371276231780d7, 0xC02Dd50b25364e747410730A1df9B72A92C3C68B, 0x286777D6ad08EbE395C377078a17a32c21564a8a, 0x00eCb19318d98ff57173Ac8EdFb7a5D90ba2005d, 0x2E169A7c3D8EBeC11D5b43Dade06Ac29FEf59cb3, 0x693B22BB92727Fb2a9a4D7e1b1D65B3E8168B774 ]; uint[] private shareList = [ 5, 5, 5, 5, 30, 25, 25 ]; constructor() Delegated() ERC721B("Goat Gauds", "GG", 0) PaymentSplitterMod( addressList, shareList ){ } //public view fallback() external payable {} function tokenURI(uint tokenId) external view override returns (string memory) { require(_exists(tokenId), "Query for nonexistent token"); return string(abi.encodePacked(_tokenURIPrefix, tokenId.toString(), _tokenURISuffix)); } //public payable function presale( uint quantity ) external payable { require( isPresaleActive, "Presale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= PRESALE_PRICE * quantity, "Ether sent is not correct" ); require( accessList[msg.sender] > 0, "Not authorized" ); uint supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); accessList[msg.sender] -= quantity; for(uint i; i < quantity; ++i){ _mint( msg.sender, supply++ ); } } function mint( uint quantity ) external payable { require( isMintActive, "Sale is not active" ); require( quantity <= MAX_ORDER, "Order too big" ); require( msg.value >= MAINSALE_PRICE * quantity, "Ether sent is not correct" ); uint supply = totalSupply(); require( supply + quantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < quantity; ++i){ _mint( msg.sender, supply++ ); } } //delegated payable function burnFrom( address owner, uint[] calldata tokenIds ) external payable onlyDelegates{ for(uint i; i < tokenIds.length; ++i ){ require( _exists( tokenIds[i] ), "Burn for nonexistent token" ); require( _owners[ tokenIds[i] ] == owner, "Owner mismatch" ); _burn( tokenIds[i] ); } } function mintTo(uint[] calldata quantity, address[] calldata recipient) external payable onlyDelegates{ require(quantity.length == recipient.length, "Must provide equal quantities and recipients" ); uint totalQuantity; uint supply = totalSupply(); for(uint i; i < quantity.length; ++i){ totalQuantity += quantity[i]; } require( supply + totalQuantity <= MAX_SUPPLY, "Mint/order exceeds supply" ); for(uint i; i < recipient.length; ++i){ for(uint j; j < quantity[i]; ++j){ _mint( recipient[i], supply++ ); } } } //delegated nonpayable function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{ require(tokenIds.length == recipients.length, "Must provide equal tokenIds and recipients" ); address to; uint tokenId; address zero = address(0); for(uint i; i < tokenIds.length; ++i ){ to = recipients[i]; require(recipients[i] != address(0), "resurrect to the zero address" ); tokenId = tokenIds[i]; require( !_exists( tokenId ), "can't resurrect existing token" ); _owners[tokenId] = to; // Clear approvals _approve(zero, tokenId); emit Transfer(zero, to, tokenId); } } function setAccessList(address[] calldata accounts, uint[] calldata quantities) external onlyDelegates{ require(accounts.length == quantities.length, "Must provide equal accounts and quantities" ); for(uint i; i < accounts.length; ++i){ accessList[ accounts[i] ] = quantities[i]; } } function setActive(bool isPresaleActive_, bool isMintActive_) external onlyDelegates{ require( isPresaleActive != isPresaleActive_ || isMintActive != isMintActive_, "New value matches old" ); isPresaleActive = isPresaleActive_; isMintActive = isMintActive_; } function setBaseURI(string calldata newPrefix, string calldata newSuffix) external onlyDelegates{ _tokenURIPrefix = newPrefix; _tokenURISuffix = newSuffix; } function setMax(uint maxOrder, uint maxSupply) external onlyDelegates{ require( MAX_ORDER != maxOrder || MAX_SUPPLY != maxSupply, "New value matches old" ); require(maxSupply >= totalSupply(), "Specified supply is lower than current balance" ); MAX_ORDER = maxOrder; MAX_SUPPLY = maxSupply; } function setPrice(uint presalePrice, uint mainsalePrice ) external onlyDelegates{ require( PRESALE_PRICE != presalePrice || MAINSALE_PRICE != mainsalePrice, "New value matches old" ); PRESALE_PRICE = presalePrice; MAINSALE_PRICE = mainsalePrice; } //owner function addPayee(address account, uint256 shares_) external onlyOwner { _addPayee(account, shares_); } function setPayee( uint index, address account, uint newShares ) external onlyOwner { _setPayee(index, account, newShares); } //internal function _burn(uint tokenId) internal override { address curOwner = ERC721B.ownerOf(tokenId); // Clear approvals _approve(owner(), tokenId); _owners[tokenId] = address(0); emit Transfer(curOwner, address(0), tokenId); } function _mint(address to, uint tokenId) internal override { _owners.push(to); emit Transfer(address(0), to, tokenId); } }
delegated nonpayable Clear approvals
function resurrect( uint[] calldata tokenIds, address[] calldata recipients ) external onlyDelegates{ require(tokenIds.length == recipients.length, "Must provide equal tokenIds and recipients" ); address to; uint tokenId; address zero = address(0); for(uint i; i < tokenIds.length; ++i ){ to = recipients[i]; require(recipients[i] != address(0), "resurrect to the zero address" ); tokenId = tokenIds[i]; require( !_exists( tokenId ), "can't resurrect existing token" ); _owners[tokenId] = to; _approve(zero, tokenId); emit Transfer(zero, to, tokenId); } }
2,149,010
./full_match/5/0x91520CCa285e6B7736E5615560B0248a18B6305c/sources/contracts/hikari.sol
we set claim for our users to get NFT/require(_amount > 0 && _amount < 6);
function claim(uint256 _amount) public { _safeMint(msg.sender, _amount); emit claimed(msg.sender, _amount); }
7,058,673
./partial_match/1/0x3a2c387b84b28F438aaF53e6d0B8e790D084D1d1/sources/CompoundStrategy.sol
Deposit asset into Compound _asset Address of asset to deposit _amount Amount of asset to deposit return amountDeposited Amount of asset that was deposited/
function deposit(address _asset, uint256 _amount) external onlyVault nonReentrant { _deposit(_asset, _amount); }
2,873,734
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // Sources flattened with hardhat v2.6.1 https://hardhat.org // File contracts/interfaces/dao/IInsureToken.sol pragma solidity 0.8.10; interface IInsureToken { function mint(address _to, uint256 _value)external returns(bool); function emergency_mint(uint256 _amountOut, address _to)external; function approve(address _spender, uint256 _value)external; function rate()external view returns(uint256); function future_epoch_time_write() external returns(uint256); } // File contracts/interfaces/dao/ILiquidityGauge.sol pragma solidity 0.8.10; interface ILiquidityGauge { function user_checkpoint(address _addr) external returns (bool); function integrate_fraction(address _addr) external view returns (uint256); } // File contracts/interfaces/dao/IGaugeController.sol pragma solidity 0.8.10; interface IGaugeController { function gauge_types(address _addr)external view returns(uint256); function get_voting_escrow()external view returns(address); function checkpoint_gauge(address addr)external; function gauge_relative_weight(address addr, uint256 time)external view returns(uint256); } // File contracts/interfaces/dao/IEmergencyMintModule.sol pragma solidity 0.8.10; interface IEmergencyMintModule { function mint(address _amount) external; function repayDebt() external; } // File contracts/interfaces/pool/IOwnership.sol pragma solidity 0.8.10; interface IOwnership { function owner() external view returns (address); function futureOwner() external view returns (address); function commitTransferOwnership(address newOwner) external; function acceptTransferOwnership() external; } // File @openzeppelin/contracts/utils/math/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // File @openzeppelin/contracts/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/Minter.sol pragma solidity 0.8.10; /*** *@title Token Minter *@author InsureDAO * SPDX-License-Identifier: MIT *@notice Used to mint InsureToken */ //dao-contracts //libraries contract Minter is ReentrancyGuard { event EmergencyMint(uint256 minted); event Minted(address indexed recipient, address gauge, uint256 minted); event SetConverter(address converter); IInsureToken public insure_token; IGaugeController public gauge_controller; IEmergencyMintModule public emergency_module; // user -> gauge -> value mapping(address => mapping(address => uint256)) public minted; //INSURE minted amount of user from specific gauge. // minter -> user -> can mint? mapping(address => mapping(address => bool)) public allowed_to_mint_for; // A can mint for B if [A => B => true]. IOwnership public immutable ownership; modifier onlyOwner() { require( ownership.owner() == msg.sender, "Caller is not allowed to operate" ); _; } constructor(address _token, address _controller, address _ownership) { insure_token = IInsureToken(_token); gauge_controller = IGaugeController(_controller); ownership = IOwnership(_ownership); } function _mint_for(address gauge_addr, address _for) internal { require( gauge_controller.gauge_types(gauge_addr) > 0, "dev: gauge is not added" ); ILiquidityGauge(gauge_addr).user_checkpoint(_for); uint256 total_mint = ILiquidityGauge(gauge_addr).integrate_fraction( _for ); //Total amount of both mintable and minted. uint256 to_mint = total_mint - minted[_for][gauge_addr]; //mint amount for this time. (total_amount - minted = mintable) if (to_mint != 0) { insure_token.mint(_for, to_mint); minted[_for][gauge_addr] = total_mint; emit Minted(_for, gauge_addr, total_mint); } } /*** *@notice Mint everything which belongs to `msg.sender` and send to them *@param gauge_addr `LiquidityGauge` address to get mintable amount from */ function mint(address gauge_addr) external nonReentrant { _mint_for(gauge_addr, msg.sender); } /*** *@notice Mint everything which belongs to `msg.sender` across multiple gauges *@param gauge_addrs List of `LiquidityGauge` addresses *@dev address[8]: 8 has randomly decided and has no meaning. */ function mint_many(address[8] memory gauge_addrs) external nonReentrant { for (uint256 i; i < 8;) { if (gauge_addrs[i] == address(0)) { break; } _mint_for(gauge_addrs[i], msg.sender); unchecked { ++i; } } } /*** *@notice Mint tokens for `_for` *@dev Only possible when `msg.sender` has been approved via `toggle_approve_mint` *@param gauge_addr `LiquidityGauge` address to get mintable amount from *@param _for Address to mint to */ function mint_for(address gauge_addr, address _for) external nonReentrant { if (allowed_to_mint_for[msg.sender][_for]) { _mint_for(gauge_addr, _for); } } /*** *@notice allow `minting_user` to mint for `msg.sender` *@param minting_user Address to toggle permission for */ function toggle_approve_mint(address minting_user) external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[ minting_user ][msg.sender]; } //-----------------emergency mint-----------------/ function set_emergency_mint_module(address _emergency_module) external onlyOwner { emergency_module = IEmergencyMintModule(_emergency_module); } /*** *@param mint_amount amount of INSURE to be minted */ function emergency_mint(uint256 _mint_amount) external { require(msg.sender == address(emergency_module), "onlyOwner"); //mint insure_token.emergency_mint(_mint_amount, address(emergency_module)); emit EmergencyMint(_mint_amount); } }
allow `minting_user` to mint for `msg.sender` minting_user Address to toggle permission for/
function toggle_approve_mint(address minting_user) external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[ minting_user ][msg.sender]; }
6,647,608
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /// SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IStakingRewards.sol"; import "../interfaces/IRewardsEscrow.sol"; // https://docs.synthetix.io/contracts/source/contracts/stakingrewards contract Staking is IStakingRewards, Ownable, ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; IRewardsEscrow public rewardsEscrow; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; // duration in seconds for rewards to be held in escrow uint256 public escrowDuration; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; mapping(address => bool) public rewardDistributors; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( IERC20 _rewardsToken, IERC20 _stakingToken, IRewardsEscrow _rewardsEscrow ) { rewardsToken = _rewardsToken; stakingToken = _stakingToken; rewardsEscrow = _rewardsEscrow; rewardDistributors[msg.sender] = true; escrowDuration = 365 days; _rewardsToken.safeIncreaseAllowance(address(_rewardsEscrow), type(uint256).max); } /* ========== VIEWS ========== */ function totalSupply() external view override returns (uint256) { return _totalSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view override returns (uint256) { return block.timestamp < periodFinish ? block.timestamp : periodFinish; } function rewardPerToken() public view override returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view override returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view override returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeFor(uint256 amount, address account) external { _stake(amount, account); } function stake(uint256 amount) external override { _stake(amount, msg.sender); } function _stake(uint256 amount, address account) internal nonReentrant whenNotPaused updateReward(account) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(account, amount); } function withdraw(uint256 amount) public override nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public override nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; uint256 payout = reward / uint256(10); uint256 escrowed = payout * uint256(9); rewardsToken.safeTransfer(msg.sender, payout); rewardsEscrow.lock(msg.sender, escrowed, escrowDuration); emit RewardPaid(msg.sender, reward); } } function exit() external override { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function setEscrowDuration(uint256 duration) external onlyOwner { emit EscrowDurationUpdated(escrowDuration, duration); escrowDuration = duration; } function notifyRewardAmount(uint256 reward) external override updateReward(address(0)) { require(rewardDistributors[msg.sender], "not authorized"); if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // handle the transfer of reward tokens via `transferFrom` to reduce the number // of transactions required and ensure correctness of the reward amount IERC20(rewardsToken).safeTransferFrom(msg.sender, address(this), reward); // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Modify approval for an address to call notifyRewardAmount function approveRewardDistributor(address _distributor, bool _approved) external onlyOwner { emit RewardDistributorUpdated(_distributor, _approved); rewardDistributors[_distributor] = _approved; } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); require(tokenAddress != address(rewardsToken), "Cannot withdraw the rewards token"); IERC20(tokenAddress).safeTransfer(owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } function setRewardsEscrow(address _rewardsEscrow) external onlyOwner { emit RewardsEscrowUpdated(address(rewardsEscrow), _rewardsEscrow); rewardsEscrow = IRewardsEscrow(_rewardsEscrow); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event RewardsEscrowUpdated(address _previous, address _new); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event EscrowDurationUpdated(uint256 _previousDuration, uint256 _newDuration); event Recovered(address token, uint256 amount); event RewardDistributorUpdated(address indexed distributor, bool approved); } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity >0.6.0; interface IRewardsEscrow { function lock( address _address, uint256 _amount, uint256 duration ) external; } // SPDX-License-Identifier: GPL-3.0 // Docgen-SOLC: 0.8.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingRewards { // Views function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; function notifyRewardAmount(uint256 reward) external; }
Modify approval for an address to call notifyRewardAmount
function approveRewardDistributor(address _distributor, bool _approved) external onlyOwner { emit RewardDistributorUpdated(_distributor, _approved); rewardDistributors[_distributor] = _approved; }
1,285,042
./full_match/43113/0x128E853EE53612a38a29AE82F12A5056de7C81E0/sources/Multiwallet.sol
Function to make amount claimable in multiwallet. mAddress Address of the person whose multiwallet is to be updated. mType Recipient Type of the person. amount Amount to be deMultiwalleted(made claimable)./
function deMultiwallet(address mAddress, Recipients mType, uint256 amount) external onlyAllowed { m_multiwallet[mType][mAddress] = m_multiwallet[mType][mAddress].sub(amount); m_claim[mType][mAddress] = m_claim[mType][mAddress].add(amount); }
7,195,540
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISunblockInvestmentVehicle /// @author Kenth Fagerlund /// @dev Interface to Sunblock Investment Vehicles. interface ISunblockInvestmentVehicle { /// @notice Allows for managers of the vehicle to deposit investment funds /// @dev Token to fund the contract is dictated by the contract itself. /// @param invPool address from where funds are deposited. /// @param _amount wei amount of supported token to deposit. function depositInvestment(address invPool, uint256 _amount) external; /// @notice Allows for managers of this vehicle to withdraw investment funds /// @dev funds withdrawn is always in the currency of the contract when it was initialized /// @param receiver address to where the funds should be sent /// @param amount wei amount of supported token to withdraw to receiver function withdrawInvestment(address receiver, uint256 amount) external; function depositReward(address _rewardPool, uint256 _amount) external; function withdrawReward(address receiver, uint256 _amount) external; function withdrawManagerFee(address receiver, uint256 _amount) external; }
ISunblockInvestmentVehicle Kenth Fagerlund Interface to Sunblock Investment Vehicles.
interface ISunblockInvestmentVehicle { function depositInvestment(address invPool, uint256 _amount) external; function withdrawInvestment(address receiver, uint256 amount) external; function depositReward(address _rewardPool, uint256 _amount) external; function withdrawReward(address receiver, uint256 _amount) external; function withdrawManagerFee(address receiver, uint256 _amount) external; pragma solidity ^0.8.0; }
5,416,073
./partial_match/5/0x0d6EbD4ffbbe639Ac4feA5255642dB0EC13E5346/sources/LendingBorrowing.sol
calculates the total due debt with interest for a given borrowed amount/
function calculateDebtWithInterest(uint256 _amount) internal view returns (uint256) { uint256 _interest = (_amount * i_interestRate) / 10**18; return _amount + _interest; }
16,857,062
pragma solidity >0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; import "@daostack/arc/contracts/controller/ControllerInterface.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "../../identity/Identity.sol"; import "../../identity/IdentityGuard.sol"; import "../../token/GoodDollar.sol"; import "./ActivePeriod.sol"; import "./FeelessScheme.sol"; /* @title Base contract template for UBI scheme */ contract AbstractUBI is ActivePeriod, FeelessScheme { using SafeMath for uint256; uint256 initialReserve; uint256 public claimDistribution; struct Day { mapping(address => bool) hasClaimed; uint256 amountOfClaimers; uint256 claimAmount; } mapping(uint256 => Day) claimDay; mapping(address => uint256) public lastClaimed; uint256 public currentDay; event UBIStarted(uint256 balance, uint256 time); event UBIClaimed(address indexed claimer, uint256 amount); event UBIEnded(uint256 claimers, uint256 claimamount); /** * @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint256 _periodStart, uint256 _periodEnd ) public ActivePeriod(_periodStart, _periodEnd, _avatar) FeelessScheme(_identity, _avatar) { initialReserve = _initialReserve; } /** * @dev function that returns an uint256 that * represents the amount each claimer can claim. * @param reserve the account balance to calculate from * @return The distribution for each claimer */ function distributionFormula(uint256 reserve, address user) internal returns (uint256); /* @dev function that gets the amount of people who claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @return an integer indicating the amount of people who claimed that day */ function getClaimerCount(uint256 day) public view returns (uint256) { return claimDay[day].amountOfClaimers; } /* @dev function that gets the amount that was claimed on the given day * @param day the day to get claimer count from, with 0 being the starting day * @return an integer indicating the amount that has been claimed on the given day */ function getClaimAmount(uint256 day) public view returns (uint256) { return claimDay[day].claimAmount; } /* @dev function that gets count of claimers and amount claimed for the current day * @return the amount of claimers and the amount claimed. */ function getDailyStats() public view returns (uint256 count, uint256 amount) { uint256 today = (now.sub(periodStart)) / 1 days; return (getClaimerCount(today), getClaimAmount(today)); } /* @dev Function that commences distribution period on contract. * Can only be called after periodStart and before periodEnd and * can only be done once. The reserve is sent * to this contract to allow claimers to claim from said reserve. * The claim distribution is then calculated and true is returned * to indicate that claiming can be done. */ function start() public onlyRegistered { super.start(); addRights(); currentDay = now.sub(periodStart) / 1 days; // Transfer the fee reserve to this contract DAOToken token = avatar.nativeToken(); if (initialReserve > 0) { require( initialReserve <= token.balanceOf(address(avatar)), "Not enough funds to start" ); controller.genericCall( address(token), abi.encodeWithSignature( "transfer(address,uint256)", address(this), initialReserve ), avatar, 0 ); } emit UBIStarted(token.balanceOf(address(this)), now); } /** * @dev Function that ends the claiming period. Can only be done if * Contract has been started and periodEnd is passed. * Sends the remaining funds on contract back to the avatar contract * address */ function end() public requirePeriodEnd { DAOToken token = avatar.nativeToken(); uint256 remainingReserve = token.balanceOf(address(this)); if (remainingReserve > 0) { require( token.transfer(address(avatar), remainingReserve), "end transfer failed" ); } removeRights(); super.end(); } /* @dev UBI claiming function. Can only be called by users that were * whitelisted before start of contract * Each claimer can only claim once per UBI contract * @return true if the user claimed successfully */ function claim() public requireActive onlyWhitelisted onlyAddedBefore(periodStart) returns (bool) { require(!claimDay[currentDay].hasClaimed[msg.sender], "has already claimed"); claimDay[currentDay].hasClaimed[msg.sender] = true; GoodDollar token = GoodDollar(address(avatar.nativeToken())); claimDay[currentDay].amountOfClaimers = claimDay[currentDay].amountOfClaimers.add( 1 ); claimDay[currentDay].claimAmount = claimDay[currentDay].claimAmount.add( claimDistribution ); lastClaimed[msg.sender] = now; require(token.transfer(msg.sender, claimDistribution), "claim transfer failed"); emit UBIClaimed(msg.sender, claimDistribution); return true; } } /* @title UBI scheme contract responsible for calculating a distribution * based on amount of whitelisted users */ contract UBI is AbstractUBI { uint256 claimers; /* @dev Constructor. Checks if avatar is a zero address * and if periodEnd variable is after periodStart. * @param _avatar the avatar contract * @param _identity the identity contract * @param _periodStart period from when the contract is able to start * @param _periodEnd period from when the contract is able to end */ constructor( Avatar _avatar, Identity _identity, uint256 _initialReserve, uint256 _periodStart, uint256 _periodEnd ) public AbstractUBI(_avatar, _identity, _initialReserve, _periodStart, _periodEnd) { claimers = (identity.whitelistedCount()).sub(identity.whitelistedContracts()); } /* @dev function that calculated the amount each claimer can claim. * amount to claim is the amount of GoodDollar contract holds * divided by amount of eligible claimers * @param reserve the account balance to calculate from * @return The reserve divided by the amount of registered claimers */ function distributionFormula( uint256 reserve, address /*user*/ ) internal returns (uint256) { return reserve.div(claimers); } /* @dev starts scheme and calculates distribution of UBI */ function start() public { super.start(); DAOToken token = avatar.nativeToken(); claimDistribution = distributionFormula( token.balanceOf(address(this)), address(0) ); } }
function that calculated the amount each claimer can claim. amount to claim is the amount of GoodDollar contract holds divided by amount of eligible claimers reserve the account balance to calculate from return The reserve divided by the amount of registered claimers/
function distributionFormula( uint256 reserve, address /*user*/ ) internal returns (uint256) { return reserve.div(claimers); }
5,351,707
pragma solidity ^0.4.11; import './SafeMath.sol'; import './Halt.sol'; import './WBTC.sol'; contract WBTCManager is Halt { using SafeMath for uint; /************************************************************ ** ** VARIABLES ** ************************************************************/ /// WBTC token address WBTC public WBTCToken; /// TotalQuota uint private totalQuota; /// StoremanGroupAdmin address address public storemanGroupAdmin; /// HTLCWBTC contract address address public HTLCWBTC; /// A mapping from StoremanGroup address to corresponding credit-line status mapping(address => StoremanGroup) public mapStoremanGroup; /// A mapping from StoremanGroup address to unregistration application status mapping(address => bool) public mapUnregistration; /// A single storemanGroup credit-line detail struct StoremanGroup { /// This storemanGroup's total quota in BTC <<<>>> WBTC pair uint _quota; /// Amount of BTC to be received, equals to amount of WBTC to be minted uint _receivable; /// Amount of BTC to be paied, equals to WBTC to be burnt uint _payable; /// Amount of BTC received, equals to amount of WBTC been minted uint _debt; } /************************************************************ ** ** MODIFIERS ** ************************************************************/ /// Authorization modifiers /// @notice `storemanGroupAdmin` is the only address that can call a function with this modifier /// @dev `storemanGroupAdmin` is the only address that can call a function with this modifier modifier onlyStoremanGroupAdmin { require(msg.sender == storemanGroupAdmin); _; } /// @notice `HTLCWBTC` is the only address that can call a function with this modifier /// @dev `HTLCWBTC` is the only address that can call a function with this modifier modifier onlyHTLCWBTC { require(msg.sender == HTLCWBTC); _; } /// Quantity modifiers /// @notice Test if a value provided is meaningless /// @dev Test if a value provided is meaningless /// @param value Given value to be handled modifier onlyMeaningfulValue(uint value) { require(value > 0); _; } /************************************************************ ** ** EVENTS ** ************************************************************/ ///@notice Log out register storemanGroup ///@dev Log out register storemanGroup ///@param storemanGroup StoremanGroup address ///@param quota BTC/WBTC quota assigned to this storemanGroup ///@param totalQuota TotalQuota after registration event StoremanGroupRegistrationLogger( address indexed storemanGroup, uint indexed quota, uint indexed totalQuota ); ///@notice Log out unregister storemanGroup ///@dev Log out unregister storemanGroup ///@param storemanGroup StoremanGroup address ///@param quota BTC/WBTC quota assigned to this storemanGroup ///@param totalQuota TotalQuota after unregistration event StoremanGroupUnregistrationLogger( address indexed storemanGroup, uint indexed quota, uint indexed totalQuota ); /** * CONSTRUCTOR * * @notice Initialize the HTLCWBTCAddr address * @param HTLCAddr The HTLCWBTC address * @param smgAdminAddr smg address */ function WBTCManager(address HTLCAddr,address smgAdminAddr) public { require(HTLCAddr != address(0)); require(smgAdminAddr != address(0)); HTLCWBTC = HTLCAddr; storemanGroupAdmin = smgAdminAddr; WBTCToken = new WBTC(this); } /**************************************************************************** ** ** MANIPULATIONS ** ****************************************************************************/ /// @notice Register a storemanGroup /// @dev Register a storemanGroup /// @param storemanGroup Address of the storemanGroup to be registered /// @param quota This storemanGroup's quota in WBTC/BTC pair /// @return Result of registering the provided address, true if successful function registerStoremanGroup(address storemanGroup, uint quota) public notHalted onlyStoremanGroupAdmin onlyMeaningfulValue(quota) returns (bool) { /// Make sure a valid storemanGroup address provided require(storemanGroup != address(0)); require(!isStoremanGroup(storemanGroup)); /// Create an instance of storemanGroup mapStoremanGroup[storemanGroup] = StoremanGroup(quota, 0, 0, 0); /// Update totalQuota totalQuota = totalQuota.add(quota); /// Fire StoremanGroupRegistrationLogger event emit StoremanGroupRegistrationLogger(storemanGroup, quota, totalQuota); return true; } /// @dev Unregister a storemanGroup /// @param storemanGroup Address of the storemanGroup to be unregistered /// @return Result of unregistering provided storemanGroup, true if successful function unregisterStoremanGroup(address storemanGroup) public notHalted onlyStoremanGroupAdmin returns (bool) { /// Make sure a valid storemanGroup address provided require(mapUnregistration[storemanGroup]); /// Make sure the given storemanGroup has paid off its debt require(isDebtPaidOff(storemanGroup)); StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; /// remove this storemanGroup from the unregistration intention map mapUnregistration[storemanGroup] = false; /// adjust total quota totalQuota = totalQuota.sub(_s._quota); /// Fire the UnregisterStoremanGroup event emit StoremanGroupUnregistrationLogger(storemanGroup, _s._quota, totalQuota); /// Reset quota _s._quota = uint(0); return true; } /// @notice StoremanGroup unregistration application /// @dev StoremanGroup unregistration application /// @param storemanGroup StoremanGroup's address function applyUnregistration(address storemanGroup) public notHalted onlyStoremanGroupAdmin returns (bool) { /// Reject unqualified storemanGroup address require(isActiveStoremanGroup(storemanGroup)); mapUnregistration[storemanGroup] = true; return true; } /// @notice Frozen WBTC quota /// @dev Frozen WBTC quota /// @param storemanGroup Handler address /// @param recipient Recipient's address, and it could be a storemanGroup applied unregistration /// @param value Amout of WBTC quota to be frozen /// @return True if successful function lockQuota(address storemanGroup, address recipient, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { /// Make sure an active storemanGroup is provided to handle transactions require(isActiveStoremanGroup(storemanGroup)); /// Make sure a valid recipient provided require(!isActiveStoremanGroup(recipient)); /// Make sure enough inbound quota available StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; require(_s._quota.sub(_s._receivable.add(_s._debt)) >= value); /// Only can be called by an unregistration applied storemanGroup reset its receivable and payable if (mapUnregistration[recipient]) { StoremanGroup storage _r = mapStoremanGroup[recipient]; require(_r._receivable == 0 && _r._payable == 0 && _r._debt != 0); } /// Increase receivable _s._receivable = _s._receivable.add(value); return true; } /// @notice Defrozen WBTC quota /// @dev Defrozen WBTC quota /// @param storemanGroup Handler address /// @param value Amount of WBTC quota to be locked /// @return True if successful function unlockQuota(address storemanGroup, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { /// Make sure a valid storeman provided require(isStoremanGroup(storemanGroup)); StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; /// Make sure this specified storemanGroup has enough inbound receivable to be unlocked require(_s._receivable >= value); /// Credit receivable, double-check receivable is no less than value to be unlocked _s._receivable = _s._receivable.sub(value); return true; } /// @notice Mint WBTC token or payoff storemanGroup debt /// @dev Mint WBTC token or payoff storemanGroup debt /// @param storemanGroup Handler address /// @param recipient Address that will receive WBTC token /// @param value Amount of WBTC token to be minted /// @return Success of token mint function mintToken(address storemanGroup, address recipient, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { /// Make sure a legit storemanGroup provided require(isStoremanGroup(storemanGroup)); /// Make sure a legit recipient provided require(!isActiveStoremanGroup(recipient)); StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; /// Adjust quota record _s._receivable = _s._receivable.sub(value); _s._debt = _s._debt.add(value); /// Branch - mint token to an ordinary account if (!isStoremanGroup(recipient)) { /// Mint token to the recipient require(WBTCToken.mint(recipient, value)); return true; } else if (mapUnregistration[recipient]) { /// Branch - storemanGroup unregistration StoremanGroup storage _r = mapStoremanGroup[recipient]; /// Adjust the unregistering smg debt if (value >= _r._debt) { _r._debt = 0; } else { _r._debt = _r._debt.sub(value); } return true; } return false; } /// @notice Lock WBTC token and initiate an outbound transaction /// @dev Lock WBTC token and initiate an outbound transaction /// @param storemanGroup Outbound storemanGroup handler address /// @param value Amount of WBTC token to be locked /// @return Success of token locking function lockToken(address storemanGroup, address initiator, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { /// Make sure a valid storemanGroup and a legit initiator provided require(isActiveStoremanGroup(storemanGroup)); require(!isStoremanGroup(initiator)); StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; /// Make sure it has enough outboundQuota require(_s._debt.sub(_s._payable) >= value); /// Adjust quota record _s._payable = _s._payable.add(value); /// Handle token transfer require(WBTCToken.lockTo(initiator, HTLCWBTC, value)); return true; } /// @notice Unlock WBTC token /// @dev Unlock WBTC token /// @param storemanGroup StoremanGroup handler address /// @param value Amount of token to be unlocked /// @return Success of token unlocking function unlockToken(address storemanGroup, address recipient, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { require(isStoremanGroup(storemanGroup)); /// Make sure it has enough quota for a token unlocking StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; require(_s._payable >= value); /// Adjust quota record _s._payable = _s._payable.sub(value); /// Handle token transfer require(WBTCToken.lockTo(HTLCWBTC, recipient, value)); return true; } /// @notice Burn WBTC token /// @dev Burn WBTC token /// @param storemanGroup Crosschain transaction handler address /// @param value Amount of WBTC token to be burnt /// @return Success of burn token function burnToken(address storemanGroup, uint value) public notHalted onlyHTLCWBTC onlyMeaningfulValue(value) returns (bool) { require(isStoremanGroup(storemanGroup)); StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; /// Adjust quota record _s._debt = _s._debt.sub(value); _s._payable = _s._payable.sub(value); /// Process the transaction require(WBTCToken.burn(HTLCWBTC, value)); return true; } /// @notice Query storemanGroup detail /// @dev Query storemanGroup detail /// @param storemanGroup StoremanGroup to be queried /// @return quota Total quota of this storemanGroup in BTC/WBTC /// @return inboundQuota Inbound crosschain transaction quota of this storemanGroup in BTC/WBTC /// @return outboundQuota Outbound crosschain transaction quota of this storemanGroup in BTC/WBTC /// @return receivable Amount of WBTC to be minted through this storemanGroup /// @return payable Amount of WBTC to be burnt through this storemanGroup /// @return debt Amount of WBTC been minted through this storemanGroup function getStoremanGroup(address storemanGroup) public view returns (uint, uint, uint, uint, uint, uint) { if (!isStoremanGroup(storemanGroup)) { return (0, 0, 0, 0, 0, 0); } StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; uint inboundQuota = _s._quota.sub(_s._receivable.add(_s._debt)); uint outboundQuota = _s._debt.sub(_s._payable); return (_s._quota, inboundQuota, outboundQuota, _s._receivable, _s._payable, _s._debt); } /// @notice Check if a specified address is a valid storemanGroup /// @dev Check if a specified address is a valid storemanGroup /// @param storemanGroup The storemanGroup's address to be checked /// @return Result of validity check, true is successful, false in case failed function isStoremanGroup(address storemanGroup) public view returns (bool) { return mapStoremanGroup[storemanGroup]._quota != uint(0); } /// @notice Check if a specified address is active to handle cross chain transaction /// @dev Check if a specified address is active to handle cross chain transaction /// @param storemanGroup The storemanGroup's address to be checked /// @return Result of validity check, true is successful, false in case failed function isActiveStoremanGroup(address storemanGroup) public view returns (bool) { return isStoremanGroup(storemanGroup) && !mapUnregistration[storemanGroup]; } /// @notice Query totalQuota /// @dev Query totalQuota /// @return Quota in BTC/WBTC function getTotalQuota() public onlyOwner view returns (uint) { return totalQuota; } /// @notice destruct SC and transfer balance to owner /// @dev destruct SC and transfer balance to owner function kill() public onlyOwner isHalted { selfdestruct(owner); } /// Private methods /// @notice Check if a specified storemanGroup has paid off its debt /// @dev Check if a specified storemanGroup has paid off its debt /// @param storemanGroup The storemanGroup's address to be checked /// @return Result of debt status check function isDebtPaidOff(address storemanGroup) private view returns (bool) { StoremanGroup storage _s = mapStoremanGroup[storemanGroup]; return _s._receivable == uint(0) && _s._payable == uint(0) && _s._debt == uint(0); } /// Fallback /// @notice If WAN coin is sent to this address, send it back. /// @dev If WAN coin is sent to this address, send it back. function () public payable { revert(); } }
Query totalQuota Query totalQuota return Quota in BTC/WBTC
function getTotalQuota() public onlyOwner view returns (uint) { return totalQuota; }
5,345,634
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./IERC721Metadata.sol"; import "./Address.sol"; import "./Context.sol"; import "./ERC165.sol"; import "./IRNG.sol"; import "./Strings.sol"; contract NobilityKnight is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // total number of NFTs Minted uint256 private _totalSupply; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // name + bio of knight struct KnightData { string name; string bio; } // knight data mapping( uint256 => KnightData ) knightData; // token stats mapping(uint256 => uint256) idToLevel; // maximum supply which can be minted uint256 public constant maxSupply = 4444; // nfts baseURL string private baseURI = "https://nftapi.nobilitytoken.com/nblknight/"; // white list spots uint256 public remainingWhitelist; uint256 public remainingStaffMints; // nobility white list nfts address private constant whitelistOne = 0x8bA27DD2621ED0ff1fF5F3513ca7aEA81511677F; address private constant whitelistTwo = 0x4F86eDcACD3B67Ab8786B030A3eEe4275c7Ca90d; uint256 private constant whitelistOneCost = 3194 * 10**14; // use wallet address public useWallet = 0xcDe5525CF7971cc28759939481FEcc9E45941ff6; // base cost to mint NFT uint256 public cost = 4444 * 10**14; // 6 month white list timeout uint256 private constant whitelistTimeout = 5_200_000; uint256 public immutable launchTime; // time requirements to upgrade to level 2 or 3 uint256 public constant timeToUpgradeToLevel3 = 5_200_000; uint256 public constant timeToUpgradeToDragon = 2_600_000; // TokenID => hasMinted mapping ( uint256 => bool ) public whitelistOneHasMinted; mapping ( uint256 => bool ) public whitelistTwoHasMinted; // when the ownership of tokenIDs changes mapping ( uint256 => uint256 ) public timeOfAcquisition; // Attacking ID -> Defending ID mapping ( uint256 => bool ) public lookingForDual; // whether dualing is enabled or not bool public dualingEnabled; // RNG to fetch salt from address private RNG; // operator address public operator; modifier onlyOperator() { require(msg.sender == operator, 'Only Operator'); _; } // has mint started bool saleStarted; // events event Battle(uint256 attackerID, uint256 defenderID, uint256 winningID); event SetUseWallet(address useWallet); /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { // token stats _name = 'Noble Knights'; _symbol = 'NBLK'; // split up mints between whitelist + non whitelisted remainingStaffMints = 30; // Remaining whitelist, no more will be minted that effect NobleKnights remainingWhitelist = 242; // time of launch launchTime = block.number; // operator operator = msg.sender; } // owner functions function transferOperator(address nOperator) external onlyOperator { operator = nOperator; } function setRNG(address newRNG) external onlyOperator { require(newRNG != address(0)); RNG = newRNG; } function setStaffMints(uint256 newStaffMints) external onlyOperator { remainingStaffMints = newStaffMints; } function setWhiteListSpots(uint256 newWhiteListSpots) external onlyOperator { remainingWhitelist = newWhiteListSpots; } function changeCost(uint256 newCost) external onlyOperator { cost = newCost; } function startSale() external onlyOperator { saleStarted = true; } function stopSale() external onlyOperator { saleStarted = false; } function changeUseWallet(address newUseWallet) external onlyOperator { useWallet = newUseWallet; emit SetUseWallet(newUseWallet); } function enableDualing() external onlyOperator { dualingEnabled = true; } function disableDualing() external onlyOperator { dualingEnabled = false; } function withdraw(address recipient) external onlyOperator { (bool s,) = payable(recipient).call{value: address(this).balance}(""); require(s); } function overrideWhitelistReservationSlots() external onlyOperator { require(launchTime + whitelistTimeout < block.number, 'Must Wait Until Timeout'); remainingWhitelist = 0; } function staffMint(address recipient) external onlyOperator { require(remainingStaffMints > 0, 'Zero Staff Mints Left'); // decrement staff mints remainingStaffMints--; // mint to recipient _safeMint(recipient, _totalSupply); } function setBaseURI(string calldata uri) external onlyOperator { baseURI = uri; } function _baseURI() internal view returns (string memory) { return baseURI; } // external functions function fetchIDSForOwner(bool _whitelistOne, address holder, uint256 whitelistTotalSupply) external view returns (uint256[] memory) { uint256 count = 0; for (uint i = 0; i < whitelistTotalSupply; i++) { if (IERC721(_whitelistOne ? whitelistOne : whitelistTwo).ownerOf(i) == holder) { if (_whitelistOne && !whitelistOneHasMinted[i]) { count++; } else if (!_whitelistOne && !whitelistTwoHasMinted[i]) { count++; } } } uint256[] memory ids = new uint256[](count); uint256 j; if (count == 0) return ids; for (uint i = 0; i < whitelistTotalSupply; i++) { if (IERC721(_whitelistOne ? whitelistOne : whitelistTwo).ownerOf(i) == holder) { if (_whitelistOne && !whitelistOneHasMinted[i]) { ids[j] = i; j++; } else if (!_whitelistOne && !whitelistTwoHasMinted[i]) { ids[j] = i; j++; } } } return ids; } function burn(uint256 tokenID) external { require(_isApprovedOrOwner(_msgSender(), tokenID), "caller not owner nor approved"); _burn(tokenID); } function upgradeToLevel3(uint256 tokenID) external { require(ownerOf(tokenID) == msg.sender, 'Not Owner'); require(idToLevel[tokenID] == 1, 'Must Be Level 2'); require(timeOfAcquisition[tokenID] + timeToUpgradeToLevel3 <= block.number, 'Hold Time Not Met'); // reset token hold timer timeOfAcquisition[tokenID] = block.number; // upgrade token ID _upgrade(tokenID); } function setLookingForDual(uint256 tokenID, bool canDual) external { require(dualingEnabled, 'Duals disabled'); require(_levelOne(tokenID), 'Only LV One'); require(ownerOf(tokenID) == msg.sender, 'Not Owner'); lookingForDual[tokenID] = canDual; } function battleKnight(uint256 attackingID, uint256 targetID) external { require(dualingEnabled, 'Duals disabled'); require(ownerOf(attackingID) == msg.sender, 'Not Owner'); require(_exists(targetID), 'Target Has No Owner'); require(_levelOne(attackingID), 'Only LV One'); require(_levelOne(targetID), 'Only LV One'); require(lookingForDual[targetID], 'Target Not Looking To Dual'); _battle(attackingID, targetID); } function battleOwnedKnights(uint256 attackingID, uint256 defendingID) external { require(dualingEnabled, 'Duals disabled'); require(ownerOf(attackingID) == msg.sender, 'Not Owner of Attacker'); require(ownerOf(defendingID) == msg.sender, 'Not Owner of Defender'); require(_levelOne(attackingID), 'Only LV One'); require(_levelOne(defendingID), 'Only LV One'); _battle(attackingID, defendingID); } function _levelOne(uint256 tokenID) internal view returns (bool) { return idToLevel[tokenID] == 0; } function setName(string calldata name_, uint256 tokenID) external { require(ownerOf(tokenID) == msg.sender, 'Invalid Owner'); knightData[tokenID].name = name_; } function setBio(string calldata bio, uint256 tokenID) external { require(ownerOf(tokenID) == msg.sender, 'Invalid Owner'); knightData[tokenID].bio = bio; } // Minting Functions // Whitelist, Staff, and Regular function whitelistMint(bool whiteListContractOne, uint256 tokenID) external payable { require(saleStarted, 'Sale Not Started'); require(remainingWhitelist > 0, 'Zero Slots Left'); if (whiteListContractOne) { require(IERC721(whitelistOne).ownerOf(tokenID) == msg.sender, 'Not Owner'); require(!whitelistOneHasMinted[tokenID], 'Whitelist Slot Already Used'); require(msg.value >= whitelistOneCost, 'Invalid ETH Sent'); whitelistOneHasMinted[tokenID] = true; } else { require(IERC721(whitelistTwo).ownerOf(tokenID) == msg.sender, 'Not Owner'); require(!whitelistTwoHasMinted[tokenID], 'Whitelist Slot Already Used'); require(msg.value >= cost, 'Invalid ETH Sent'); whitelistTwoHasMinted[tokenID] = true; } // decrement remaining white list spots remainingWhitelist--; // mint to sender _safeMint(msg.sender, _totalSupply); } /** * Mints New NFT To Caller */ function mint(uint256 nMints) external payable { require(saleStarted, 'Sale Not Started'); require(nMints > 0 && nMints <= 10, '10 Knights Max In One Mint'); require(_totalSupply + remainingStaffMints + remainingWhitelist < maxSupply, 'Max NFTs Minted'); require(msg.value >= cost * nMints, 'Invalid ETH Sent'); for (uint i = 0; i < nMints; i++) { _safeMint(msg.sender, _totalSupply); } (bool s,) = payable(useWallet).call{value: address(this).balance}(""); require(s, 'Failure On ETH Payment'); } receive() external payable {} // internal functions function _battle(uint256 attackingID, uint256 defendingID) internal { // calculate rng uint256 rng = IRNG(RNG).fetchRandom(uint256(uint160(ownerOf(attackingID))), uint256(uint160(ownerOf(defendingID)))) % 2; // remove dual delete lookingForDual[attackingID]; delete lookingForDual[defendingID]; // upgrade winner _upgrade( rng == 0 ? attackingID : defendingID); // burn loser _burn( rng == 0 ? defendingID : attackingID); // emit event emit Battle(attackingID, defendingID, rng == 0 ? attackingID : defendingID); } function _upgrade(uint256 tokenId) internal { require(idToLevel[tokenId] < 2, 'Max Knight Level'); idToLevel[tokenId]++; } // read functions function timeLeftUntilUpgrade(uint256 tokenID) external view returns (uint256) { if (idToLevel[tokenID] == 0 || ownerOf(tokenID) == address(0)) return 0; if (idToLevel[tokenID] == 1) { return block.number > timeOfAcquisition[tokenID] + timeToUpgradeToLevel3 ? 0 : timeOfAcquisition[tokenID] + timeToUpgradeToLevel3 - block.number; } else { return block.number > timeOfAcquisition[tokenID] + timeToUpgradeToDragon ? 0 : timeOfAcquisition[tokenID] + timeToUpgradeToDragon - block.number; } } function totalSupply() external view returns (uint256) { return _totalSupply; } function soldOut() external view returns (bool) { return _totalSupply == maxSupply; } function getIDsByOwner(address owner) external view returns (uint256[] memory) { uint256[] memory ids = new uint256[](balanceOf(owner)); if (balanceOf(owner) == 0) return ids; uint256 count = 0; for (uint i = 0; i < _totalSupply; i++) { if (ownerOf(i) == owner) { ids[count] = i; count++; } } return ids; } function fetchIDSLookingToDual() external view returns (uint256[] memory) { uint256 count = 0; for (uint i = 0; i < _totalSupply; i++) { if (lookingForDual[i]) { count++; } } uint256[] memory ids = new uint256[](count); uint256 j; for (uint i = 0; i < _totalSupply; i++) { if (lookingForDual[i]) { ids[j] = i; j++; } } return ids; } function fetchIDSLookingToDualInIDRange(uint256 lowerBound, uint256 upperBound) external view returns (uint256[] memory) { uint256 count = 0; for (uint i = lowerBound; i < upperBound; i++) { if (lookingForDual[i]) { count++; } } uint256[] memory ids = new uint256[](count); uint256 j; for (uint i = lowerBound; i < upperBound; i++) { if (lookingForDual[i]) { ids[j] = i; j++; } } return ids; } function getLevel(uint256 tokenId) external view returns (uint256) { return idToLevel[tokenId]+1; } function canUpgradeToDragon(uint256 tokenID) external view returns (bool) { return idToLevel[tokenID] == 2 && ownerOf(tokenID) != address(0) && timeOfAcquisition[tokenID] + timeToUpgradeToDragon <= block.number; } function getName(uint256 tokenID) external view returns (string memory) { return knightData[tokenID].name; } function getBio(uint256 tokenID) external view returns (string memory) { return knightData[tokenID].bio; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address wpowner) public view override returns (uint256) { require(wpowner != address(0), "query for the zero address"); return _balances[wpowner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { address wpowner = _owners[tokenId]; require(wpowner != address(0), "query for nonexistent token"); return wpowner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "nonexistent token"); string memory _base = _baseURI(); return string(abi.encodePacked(_base, tokenId.toString())); } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address wpowner = ownerOf(tokenId); require(to != wpowner, "ERC721: approval to current owner"); require( _msgSender() == wpowner || isApprovedForAll(wpowner, _msgSender()), "ERC721: not approved or owner" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address _operator, bool approved) public override { _setApprovalForAll(_msgSender(), _operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address wpowner, address _operator) public view override returns (bool) { return _operatorApprovals[wpowner][_operator]; } /** * @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 { require(_exists(tokenId), 'Token Does Not Exist'); // owner of token address owner = ownerOf(tokenId); // Clear approvals _approve(address(0), tokenId); delete timeOfAcquisition[tokenId]; delete knightData[tokenId]; delete lookingForDual[tokenId]; // decrement balance _balances[owner] -= 1; delete _owners[tokenId]; // emit transfer emit Transfer(owner, address(0), tokenId); } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { require(_isApprovedOrOwner(_msgSender(), tokenId), "caller 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 { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: 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 returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: nonexistent token"); address wpowner = ownerOf(tokenId); return (spender == wpowner || getApproved(tokenId) == spender || isApprovedForAll(wpowner, spender)); } /** * @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 ) internal { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, ""), "ERC721: 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 { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); require(_totalSupply < maxSupply, 'Max NFTs Minted'); _balances[to] += 1; _owners[tokenId] = to; _totalSupply++; timeOfAcquisition[tokenId] = block.number; emit Transfer(address(0), to, 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 { require(ownerOf(tokenId) == from, "Incorrect owner"); require(to != address(0), "zero address"); require(balanceOf(from) > 0, 'Zero Balance'); // Clear approvals from the previous owner _approve(address(0), tokenId); // reset name + bio delete knightData[tokenId]; delete lookingForDual[tokenId]; // Allocate balances _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; timeOfAcquisition[tokenId] = block.number; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address wpowner, address _operator, bool approved ) internal { require(wpowner != _operator, "ERC721: approve to caller"); _operatorApprovals[wpowner][_operator] = approved; emit ApprovalForAll(wpowner, _operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } }
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ owner of token Clear approvals decrement balance emit transfer
function _burn(uint256 tokenId) internal { require(_exists(tokenId), 'Token Does Not Exist'); address owner = ownerOf(tokenId); _approve(address(0), tokenId); delete timeOfAcquisition[tokenId]; delete knightData[tokenId]; delete lookingForDual[tokenId]; _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); }
13,055,531
./partial_match/3/0xaAa6cfeCb86A8A8CD9E6A76f7EB8fd587B9EC090/sources/TermPoolInner.sol
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) { bytes32 initCodeHash; assembly { switch chainid() } (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash }
5,143,309
./partial_match/1/0xdcCFbB961175D7A398db8cFa867376341C3715b9/sources/ORDINATO.sol
once enabled, can never be turned off
function initORDN() external onlyOwner { isTrading = true; swapEnabled = true; taxTill = block.number + 0; }
9,158,661
./full_match/43113/0xb30496ADD15e3AB389ae310dbD654BBA772010e1/sources/cross-tool/ProxyBase.sol
pause or start the contract _state The address of the storeman entry contract/
function _setPaused(bool _state) public onlyAdmin { require(msg.sender == admin, "only admin can pause"); require(_state != pause, pause == true ?"paused already":"unpaused already"); pause = _state; emit ActionPaused(_state); }
7,108,875
./partial_match/4/0x22Eee33306501a3Df59731EE356e0ef980c9b4E0/sources/SirenToken.sol
Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transferFrom( address src, address dst, uint256 rawAmount ) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96( rawAmount, "Siren::approve: amount exceeds 96 bits" ); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96( spenderAllowance, amount, "Siren::transferFrom: transfer amount exceeds spender allowance" ); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; }
8,618,292
pragma solidity ^0.4.24; pragma experimental ABIEncoderV2; import "./CvcOntologyInterface.sol"; import "../upgradeability/Initializable.sol"; import "../upgradeability/Ownable.sol"; import "../upgradeability/EternalStorage.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title CvcOntology * @dev This contract holds the list of all recognized Credential Items available for sale. */ contract CvcOntology is EternalStorage, Initializable, Ownable, CvcOntologyInterface { using SafeMath for uint256; /** Data structures and storage layout: struct CredentialItem { string type; // "claim" or "credential" string name; // e.g. "proofOfIdentity" string version; // e.g. "v1.2" string reference; // e.g. "https://example.com/credential-proofOfIdentity-v1_2.json" string referenceType; // e.g. "JSON-LD-Context" bytes32 referenceHash; // e.g. "0x2cd9bf92c5e20b1b410f5ace94d963a96e89156fbe65b70365e8596b37f1f165" bool deprecated; // e.g. false } uint256 recordsCount; bytes32[] recordsIds; mapping(bytes32 => CredentialItem) records; **/ /** * Constructor to initialize with some default values */ constructor() public { initialize(msg.sender); } /** * @dev Adds new Credential Item to the registry. * @param _recordType Credential Item type * @param _recordName Credential Item name * @param _recordVersion Credential Item version * @param _reference Credential Item reference URL * @param _referenceType Credential Item reference type * @param _referenceHash Credential Item reference hash */ function add( string _recordType, string _recordName, string _recordVersion, string _reference, string _referenceType, bytes32 _referenceHash ) external onlyInitialized onlyOwner { require(bytes(_recordType).length > 0, "Empty credential item type"); require(bytes(_recordName).length > 0, "Empty credential item name"); require(bytes(_recordVersion).length > 0, "Empty credential item version"); require(bytes(_reference).length > 0, "Empty credential item reference"); require(bytes(_referenceType).length > 0, "Empty credential item type"); require(_referenceHash != 0x0, "Empty credential item reference hash"); bytes32 id = calculateId(_recordType, _recordName, _recordVersion); require(getReferenceHash(id) == 0x0, "Credential item record already exists"); setType(id, _recordType); setName(id, _recordName); setVersion(id, _recordVersion); setReference(id, _reference); setReferenceType(id, _referenceType); setReferenceHash(id, _referenceHash); setRecordId(getCount(), id); incrementCount(); } /** * @dev Contract initialization method. * @param _owner Contract owner address */ function initialize(address _owner) public initializes { setOwner(_owner); } /** * @dev Deprecates single Credential Item of specific type, name and version. * @param _type Record type to deprecate * @param _name Record name to deprecate * @param _version Record version to deprecate */ function deprecate(string _type, string _name, string _version) public onlyInitialized onlyOwner { deprecateById(calculateId(_type, _name, _version)); } /** * @dev Deprecates single Credential Item by ontology record ID. * @param _id Ontology record ID */ function deprecateById(bytes32 _id) public onlyInitialized onlyOwner { require(getReferenceHash(_id) != 0x0, "Cannot deprecate unknown credential item"); require(getDeprecated(_id) == false, "Credential item is already deprecated"); setDeprecated(_id); } /** * @dev Returns single Credential Item data up by ontology record ID. * @param _id Ontology record ID to search by * @return id Ontology record ID * @return recordType Credential Item type * @return recordName Credential Item name * @return recordVersion Credential Item version * @return reference Credential Item reference URL * @return referenceType Credential Item reference type * @return referenceHash Credential Item reference hash * @return deprecated Credential Item type deprecation flag */ function getById( bytes32 _id ) public view onlyInitialized returns ( bytes32 id, string recordType, string recordName, string recordVersion, string reference, string referenceType, bytes32 referenceHash, bool deprecated ) { referenceHash = getReferenceHash(_id); if (referenceHash != 0x0) { recordType = getType(_id); recordName = getName(_id); recordVersion = getVersion(_id); reference = getReference(_id); referenceType = getReferenceType(_id); deprecated = getDeprecated(_id); id = _id; } } /** * @dev Returns single Credential Item of specific type, name and version. * @param _type Credential Item type * @param _name Credential Item name * @param _version Credential Item version * @return id Ontology record ID * @return recordType Credential Item type * @return recordName Credential Item name * @return recordVersion Credential Item version * @return reference Credential Item reference URL * @return referenceType Credential Item reference type * @return referenceHash Credential Item reference hash * @return deprecated Credential Item type deprecation flag */ function getByTypeNameVersion( string _type, string _name, string _version ) public view onlyInitialized returns ( bytes32 id, string recordType, string recordName, string recordVersion, string reference, string referenceType, bytes32 referenceHash, bool deprecated ) { return getById(calculateId(_type, _name, _version)); } /** * @dev Returns all records. Currently is supported only from internal calls. * @return CredentialItem[] */ function getAll() public view onlyInitialized returns (CredentialItem[]) { uint256 count = getCount(); bytes32 id; CredentialItem[] memory records = new CredentialItem[](count); for (uint256 i = 0; i < count; i++) { id = getRecordId(i); records[i] = CredentialItem( id, getType(id), getName(id), getVersion(id), getReference(id), getReferenceType(id), getReferenceHash(id) ); } return records; } /** * @dev Returns all ontology record IDs. * Could be used from web3.js to retrieve the list of all records. * @return bytes32[] */ function getAllIds() public view onlyInitialized returns(bytes32[]) { uint256 count = getCount(); bytes32[] memory ids = new bytes32[](count); for (uint256 i = 0; i < count; i++) { ids[i] = getRecordId(i); } return ids; } /** * @dev Returns the number of registered ontology records. * @return uint256 */ function getCount() internal view returns (uint256) { // return recordsCount; return uintStorage[keccak256("records.count")]; } /** * @dev Increments total record count. */ function incrementCount() internal { // recordsCount = getCount().add(1); uintStorage[keccak256("records.count")] = getCount().add(1); } /** * @dev Returns the ontology record ID by numeric index. * @return bytes32 */ function getRecordId(uint256 _index) internal view returns (bytes32) { // return recordsIds[_index]; return bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))]; } /** * @dev Saves ontology record ID against the index. * @param _index Numeric index. * @param _id Ontology record ID. */ function setRecordId(uint256 _index, bytes32 _id) internal { // recordsIds[_index] = _id; bytes32Storage[keccak256(abi.encodePacked("records.ids.", _index))] = _id; } /** * @dev Returns the Credential Item type. * @return string */ function getType(bytes32 _id) internal view returns (string) { // return records[_id].type; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))]; } /** * @dev Saves Credential Item type. * @param _id Ontology record ID. * @param _type Credential Item type. */ function setType(bytes32 _id, string _type) internal { // records[_id].type = _type; stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))] = _type; } /** * @dev Returns the Credential Item name. * @return string */ function getName(bytes32 _id) internal view returns (string) { // records[_id].name; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))]; } /** * @dev Saves Credential Item name. * @param _id Ontology record ID. * @param _name Credential Item name. */ function setName(bytes32 _id, string _name) internal { // records[_id].name = _name; stringStorage[keccak256(abi.encodePacked("records.", _id, ".name"))] = _name; } /** * @dev Returns the Credential Item version. * @return string */ function getVersion(bytes32 _id) internal view returns (string) { // return records[_id].version; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))]; } /** * @dev Saves Credential Item version. * @param _id Ontology record ID. * @param _version Credential Item version. */ function setVersion(bytes32 _id, string _version) internal { // records[_id].version = _version; stringStorage[keccak256(abi.encodePacked("records.", _id, ".version"))] = _version; } /** * @dev Returns the Credential Item reference URL. * @return string */ function getReference(bytes32 _id) internal view returns (string) { // return records[_id].reference; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))]; } /** * @dev Saves Credential Item reference URL. * @param _id Ontology record ID. * @param _reference Reference value. */ function setReference(bytes32 _id, string _reference) internal { // records[_id].reference = _reference; stringStorage[keccak256(abi.encodePacked("records.", _id, ".reference"))] = _reference; } /** * @dev Returns the Credential Item reference type value. * @return string */ function getReferenceType(bytes32 _id) internal view returns (string) { // return records[_id].referenceType; return stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))]; } /** * @dev Saves Credential Item reference type. * @param _id Ontology record ID. * @param _referenceType Reference type. */ function setReferenceType(bytes32 _id, string _referenceType) internal { // records[_id].referenceType = _referenceType; stringStorage[keccak256(abi.encodePacked("records.", _id, ".referenceType"))] = _referenceType; } /** * @dev Returns the Credential Item reference hash value. * @return bytes32 */ function getReferenceHash(bytes32 _id) internal view returns (bytes32) { // return records[_id].referenceHash; return bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))]; } /** * @dev Saves Credential Item reference hash. * @param _id Ontology record ID. * @param _referenceHash Reference hash. */ function setReferenceHash(bytes32 _id, bytes32 _referenceHash) internal { // records[_id].referenceHash = _referenceHash; bytes32Storage[keccak256(abi.encodePacked("records.", _id, ".referenceHash"))] = _referenceHash; } /** * @dev Returns the Credential Item deprecation flag value. * @return bool */ function getDeprecated(bytes32 _id) internal view returns (bool) { // return records[_id].deprecated; return boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))]; } /** * @dev Sets Credential Item deprecation flag value. * @param _id Ontology record ID. */ function setDeprecated(bytes32 _id) internal { // records[_id].deprecated = true; boolStorage[keccak256(abi.encodePacked("records.", _id, ".deprecated"))] = true; } /** * @dev Calculates ontology record ID. * @param _type Credential Item type. * @param _name Credential Item name. * @param _version Credential Item version. */ function calculateId(string _type, string _name, string _version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_type, ".", _name, ".", _version)); } }
Returns the Credential Item type. return string/ return records[_id].type;
function getType(bytes32 _id) internal view returns (string) { return stringStorage[keccak256(abi.encodePacked("records.", _id, ".type"))]; }
14,016,864
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.4.26; /** * @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; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.4.26; // Interface declarations /* solhint-disable func-order */ interface IERC20 { // 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, uint value); // 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, uint value); // Returns the amount of tokens in existence function totalSupply() external view returns (uint); // Returns the amount of tokens owned by account function balanceOf(address account) external view returns (uint); // 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 (uint); // Sets amount as the allowance of spender over the caller’s tokens // Returns a boolean value indicating whether the operation succeeded // Emits an Approval event. function approve(address spender, uint amount) external returns (bool); // 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, uint amount) external returns (bool); // 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, uint amount) external returns (bool); } // Copyright (C) 2017 MixBytes, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). // Code taken from https://github.com/ethereum/dapp-bin/blob/master/wallet/wallet.sol // Audit, refactoring and improvements by github.com/Eenae // @authors: // Gav Wood <[email protected]> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. pragma solidity ^0.4.26; /// note: during any ownership changes all pending operations (waiting for more signatures) are cancelled // TODO acceptOwnership contract multiowned { // TYPES // struct for the status of a pending operation. struct MultiOwnedOperationPendingState { // count of confirmations needed uint yetNeeded; // bitmap of confirmations where owner #ownerIndex's decision corresponds to 2**ownerIndex bit uint ownersDone; // position of this operation key in m_multiOwnedPendingIndex uint index; } // EVENTS event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event FinalConfirmation(address owner, bytes32 operation); event Op(bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { require(isOwner(msg.sender)); _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) { _; } // Even if required number of confirmations has't been collected yet, // we can't throw here - because changes to the state have to be preserved. // But, confirmAndCheck itself will throw in case sender is not an owner. } modifier onlyallowners(bytes32 _operation) { if (confirmAndCheckForAll(_operation)) { _; } } modifier onlyalmostallowners(bytes32 _operation) { if (confirmAndCheckForAlmostAll(_operation)) { _; } } modifier validNumOwners(uint _numOwners) { require(_numOwners > 0 && _numOwners <= c_maxOwners); _; } modifier multiOwnedValidRequirement(uint _required, uint _numOwners) { require(_required > 0 && _required <= _numOwners); _; } modifier ownerExists(address _address) { require(isOwner(_address)); _; } modifier ownerDoesNotExist(address _address) { require(!isOwner(_address)); _; } modifier multiOwnedOperationIsActive(bytes32 _operation) { require(isOperationActive(_operation)); _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!). constructor(address[] _owners, uint _required) public validNumOwners(_owners.length) multiOwnedValidRequirement(_required, _owners.length) { assert(c_maxOwners <= 255); require(_owners.length == 6, "Gath3r: Number of total multisig owners must be equal to 6"); require(_required == 3, "Gath3r: Number of required multisig owners must be equal to 3"); m_numOwners = _owners.length; m_multiOwnedRequired = _required; for (uint i = 0; i < _owners.length; ++i) { address owner = _owners[i]; // invalid and duplicate addresses are not allowed require(0 != owner && !isOwner(owner) /* not isOwner yet! */); uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */); m_owners[currentOwnerIndex] = owner; m_ownerIndex[owner] = currentOwnerIndex; } assertOwnersAreConsistent(); } /// @notice replaces an owner `_from` with another `_to`. /// @param _from address of owner to replace /// @param _to address of new owner // All pending operations will be canceled! function changeOwner(address _from, address _to) external ownerExists(_from) ownerDoesNotExist(_to) onlyalmostallowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_from]); m_owners[ownerIndex] = _to; m_ownerIndex[_from] = 0; m_ownerIndex[_to] = ownerIndex; assertOwnersAreConsistent(); emit OwnerChanged(_from, _to); } /// @notice adds an owner /// @param _owner address of new owner // All pending operations will be canceled! function addOwner(address _owner) external ownerDoesNotExist(_owner) validNumOwners(m_numOwners + 1) onlyalmostallowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); m_numOwners++; m_owners[m_numOwners] = _owner; m_ownerIndex[_owner] = checkOwnerIndex(m_numOwners); assertOwnersAreConsistent(); OwnerAdded(_owner); } /// @notice removes an owner /// @param _owner address of owner to remove // All pending operations will be canceled! function removeOwner(address _owner) external ownerExists(_owner) validNumOwners(m_numOwners - 1) multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1) onlyalmostallowners(keccak256(msg.data)) { assertOwnersAreConsistent(); clearPending(); uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]); m_owners[ownerIndex] = 0; m_ownerIndex[_owner] = 0; //make sure m_numOwners is equal to the number of owners and always points to the last owner reorganizeOwners(); assertOwnersAreConsistent(); OwnerRemoved(_owner); } /// @notice changes the required number of owner signatures /// @param _newRequired new number of signatures required // All pending operations will be canceled! function changeRequirement(uint _newRequired) external multiOwnedValidRequirement(_newRequired, m_numOwners) onlymanyowners(keccak256(msg.data)) { m_multiOwnedRequired = _newRequired; clearPending(); RequirementChanged(_newRequired); } /// @notice Gets an owner by 0-indexed position /// @param ownerIndex 0-indexed owner position function getOwner(uint ownerIndex) public view returns (address) { return m_owners[ownerIndex + 1]; } /// @notice Gets owners /// @return memory array of owners function getOwners() public view returns (address[]) { address[] memory result = new address[](m_numOwners); for (uint i = 0; i < m_numOwners; i++) result[i] = getOwner(i); return result; } /// @notice checks if provided address is an owner address /// @param _addr address to check /// @return true if it's an owner function isOwner(address _addr) public view returns (bool) { return m_ownerIndex[_addr] > 0; } /// @notice Tests ownership of the current caller. /// @return true if it's an owner // It's advisable to call it by new owner to make sure that the same erroneous address is not copy-pasted to // addOwner/changeOwner and to isOwner. function amIOwner() external view onlyowner returns (bool) { return true; } /// @notice Revokes a prior confirmation of the given operation /// @param _operation operation value, typically keccak256(msg.data) function revoke(bytes32 _operation) external multiOwnedOperationIsActive(_operation) onlyowner { uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; require(pending.ownersDone & ownerIndexBit > 0); assertOperationIsConsistent(_operation); pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; assertOperationIsConsistent(_operation); Revoke(msg.sender, _operation); } /// @notice Checks if owner confirmed given operation /// @param _operation operation value, typically keccak256(msg.data) /// @param _owner an owner address function hasConfirmed(bytes32 _operation, address _owner) external view multiOwnedOperationIsActive(_operation) ownerExists(_owner) returns (bool) { return !(m_multiOwnedPending[_operation].ownersDone & makeOwnerBitmapBit(_owner) == 0); } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_multiOwnedRequired; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistent(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistent(_operation); Confirmation(msg.sender, _operation); } } } function confirmAndCheckForAll(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_numOwners; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistentForAll(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistentForAll(_operation); Confirmation(msg.sender, _operation); } } } function confirmAndCheckForAlmostAll(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) // In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point // we won't be able to do it because of block gas limit. // Yes, pending confirmations will be lost. Dont see any security or stability implications. // TODO use more graceful approach like compact or removal of clearPending completely clearPending(); MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (! isOperationActive(_operation)) { // reset count of confirmations needed. pending.yetNeeded = m_numOwners - 1; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistentForAlmostAll(_operation); } // determine the bit to set for this owner. uint ownerIndexBit = makeOwnerBitmapBit(msg.sender); // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { // ok - check if count is enough to go ahead. assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { // enough confirmations: reset and run interior. delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistentForAlmostAll(_operation); Confirmation(msg.sender, _operation); } } } // Reclaims free slots between valid owners in m_owners. // TODO given that its called after each removal, it could be simplified. function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { // iterating to the first free slot from the beginning while (free < m_numOwners && m_owners[free] != 0) free++; // iterating to the first occupied slot from the end while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; // swap, if possible, so free slot is located at the end after the swap if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { // owners between swapped slots should't be renumbered - that saves a lot of gas m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() private onlyowner { uint length = m_multiOwnedPendingIndex.length; // TODO block gas limit for (uint i = 0; i < length; ++i) { if (m_multiOwnedPendingIndex[i] != 0) delete m_multiOwnedPending[m_multiOwnedPendingIndex[i]]; } delete m_multiOwnedPendingIndex; } function checkOwnerIndex(uint ownerIndex) private pure returns (uint) { assert(0 != ownerIndex && ownerIndex <= c_maxOwners); return ownerIndex; } function makeOwnerBitmapBit(address owner) private view returns (uint) { uint ownerIndex = checkOwnerIndex(m_ownerIndex[owner]); return 2 ** ownerIndex; } function isOperationActive(bytes32 _operation) private view returns (bool) { return 0 != m_multiOwnedPending[_operation].yetNeeded; } function assertOwnersAreConsistent() private view { assert(m_numOwners > 0); assert(m_numOwners <= c_maxOwners); assert(m_owners[0] == 0); assert(0 != m_multiOwnedRequired && m_multiOwnedRequired <= m_numOwners); } function assertOperationIsConsistent(bytes32 _operation) private view { MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_multiOwnedRequired); } function assertOperationIsConsistentForAll(bytes32 _operation) private view { MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_numOwners); } function assertOperationIsConsistentForAlmostAll(bytes32 _operation) private view { MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; assert(0 != pending.yetNeeded); assert(m_multiOwnedPendingIndex[pending.index] == _operation); assert(pending.yetNeeded <= m_numOwners - 1); } // FIELDS uint constant c_maxOwners = 250; // the number of owners that must confirm the same operation before it is run. uint256 public m_multiOwnedRequired; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners (addresses), // slot 0 is unused so there are no owner which index is 0. // TODO could we save space at the end of the array for the common case of <10 owners? and should we? address[256] internal m_owners; // index on the list of owners to allow reverse lookup: owner address => index in m_owners mapping(address => uint) internal m_ownerIndex; // the ongoing operations. mapping(bytes32 => MultiOwnedOperationPendingState) internal m_multiOwnedPending; bytes32[] internal m_multiOwnedPendingIndex; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.4.26; contract TokenHolder is multiowned { using SafeMath for uint256; IERC20 public token; event Transferred(address to, uint256 amount); constructor (address[] _owners, uint _required, address _token) multiowned(_owners, _required) public { token = IERC20(_token); } function transferTokensTo(address _address, uint256 _amount) external onlymanyowners(keccak256(msg.data)) { token.transfer(_address, _amount); emit Transferred(_address, _amount); } }
In case m_multiOwnedPendingIndex grows too much we have to shrink it: otherwise at some point we won't be able to do it because of block gas limit. Yes, pending confirmations will be lost. Dont see any security or stability implications. TODO use more graceful approach like compact or removal of clearPending completely if we're not yet working on this operation, switch over and reset the confirmation status. reset count of confirmations needed. reset which owners have confirmed (none) - set our bitmap to 0. make sure we (the message sender) haven't confirmed this operation previously. ok - check if count is enough to go ahead. enough confirmations: reset and run interior. not enough: record that this owner in particular confirmed.
function confirmAndCheckForAll(bytes32 _operation) private onlyowner returns (bool) { if (512 == m_multiOwnedPendingIndex.length) clearPending(); MultiOwnedOperationPendingState pending = m_multiOwnedPending[_operation]; if (! isOperationActive(_operation)) { pending.yetNeeded = m_numOwners; pending.ownersDone = 0; pending.index = m_multiOwnedPendingIndex.length++; m_multiOwnedPendingIndex[pending.index] = _operation; assertOperationIsConsistentForAll(_operation); } if (pending.ownersDone & ownerIndexBit == 0) { assert(pending.yetNeeded > 0); if (pending.yetNeeded == 1) { delete m_multiOwnedPendingIndex[m_multiOwnedPending[_operation].index]; delete m_multiOwnedPending[_operation]; FinalConfirmation(msg.sender, _operation); return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; assertOperationIsConsistentForAll(_operation); Confirmation(msg.sender, _operation); } } }
149,293
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @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]; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /* * @dev 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; } } /** * @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; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // Accessing the Ownable method ensures that only the creator of this Smart contract can interact with it contract StreetPuppies is ERC721Enumerable, Ownable { using Strings for uint256; uint256 public constant MAX_PURCHASE = 5; uint256 public enableGenesis; uint256 public enablePresales; uint256 public immutable maxSupply; uint256 public maxGSupply; string currentcontractURI = "https://metadata.streetdawgs.io/contract/puppies"; uint256 public genesisPrice = 0.05 ether; uint256 public presalePrice = 0; uint256 public ddPrice = 0; mapping (address => uint) public presaleAddress; address public winner; string private _baseTokenURI; event Mint( address indexed to, uint256 indexed id); constructor( uint256 allowPresales, uint256 allowGenesis, uint256 maxPuppies, uint256 maxGenesisSupply ) ERC721("StreetPuppies", "SP") { enablePresales = allowPresales; enableGenesis = allowGenesis; maxSupply = maxPuppies; maxGSupply = maxGenesisSupply; } function createPuppies(uint amount) external payable returns (bool) { require(enableGenesis == 1, "CP: Sale not started"); require(amount > 0, "CP: value > zero required"); require(amount <= MAX_PURCHASE, "CP: value must not be larger than allowed"); require(totalSupply() + amount <= maxGSupply, "CP: creation must not exceed maximum supply"); require(genesisPrice * amount == msg.value, "CP: value must match accumulated price"); uint256 tokensGenerated = 0; for (uint256 i = 0; i < amount; i++) { uint256 mintIndex = totalSupply(); if (totalSupply() < maxGSupply) { _safeMint(_msgSender(), mintIndex); emit Mint(_msgSender(), mintIndex); tokensGenerated++; } } if(tokensGenerated < amount) { // amount to refund uint256 excess = amount - tokensGenerated; uint256 returnAmount = genesisPrice * excess; payable(_msgSender()).transfer(returnAmount); } return true; } /* * Send free token to an array of addresses when ever want to as owner of the contract */ function airDropPuppies(address[] calldata addresses) external onlyOwner returns (bool) { // uint count = addresses.length(); uint arrayLength = addresses.length; uint256 mintIndex = totalSupply(); for (uint i=0; i<arrayLength; i++) { if (totalSupply() < maxSupply) { _safeMint(addresses[i], mintIndex); emit Mint(addresses[i], mintIndex); mintIndex = totalSupply(); } } return true; } function createPPuppies() external payable returns (bool) { require(enablePresales == 1, "CPP: Sale not started"); require(presalePrice == msg.value, "CPP: value must match price"); require(presaleAddress[_msgSender()] > 0, "CPP: Not Authorised to buy"); require(totalSupply() <= maxSupply, "CPP: creation must not exceed maximum supply"); uint256 mintIndex = totalSupply(); if (totalSupply() < maxGSupply) { _safeMint(_msgSender(), mintIndex); presaleAddress[_msgSender()] -= 1; emit Mint(_msgSender(), mintIndex); } return true; } function createDDPuppies() external payable returns (bool) { require(totalSupply() < maxSupply, "CDDP: creation must not exceed maximum supply"); require((ddPrice == msg.value), "CDDP: value must match the daily drop price"); require(winner == _msgSender(), "CDDP: buyer address should be DD winner"); uint256 mintIndex = totalSupply(); _safeMint(_msgSender(), mintIndex); emit Mint(_msgSender(), mintIndex); delete winner; return true; } function registerForPreSale(address[] calldata addresses) external onlyOwner returns (bool){ uint arrayLength = addresses.length; for (uint i=0; i<arrayLength; i++) { presaleAddress[addresses[i]] += 1; } return true; } function withdrawFunds(uint256 withdrawAmount) external onlyOwner returns (bool) { uint256 balance = address(this).balance; require(balance > 0, "withdrawFunds: must have funds to withdraw"); require(withdrawAmount <= balance, "Can not withdraw more than available"); payable(msg.sender).transfer(withdrawAmount); return true; } function transferFund(uint256 transferAmount, address transferTo) external onlyOwner returns (bool){ uint256 amount = address(this).balance; require(transferAmount <= amount, "Can not withdraw more than available"); (bool success,) = transferTo.call{value: transferAmount}(""); require(success, "Failed to send ether"); return true; } function setBaseURI(string memory baseURI) external onlyOwner returns (bool) { _baseTokenURI = baseURI; return true; } function updateContractURI(string memory newContractURI) external onlyOwner returns (bool){ currentcontractURI = newContractURI; return true; } function setDDWinnerAndPrice(address addr, uint256 amount) external onlyOwner returns (bool) { require(addr != address(0), "setWinnerAndPrice: winner must not be the zero address"); _setDDWinner(addr); _setDDPrice(amount); return true; } function updatePreSaleList(address preAdd, uint allowedCount) external onlyOwner returns (bool){ presaleAddress[preAdd] = allowedCount; return true; } function setGPrice(uint256 amount) external onlyOwner returns (bool) { genesisPrice = amount; return true; } function setPPrice(uint256 amount) external onlyOwner returns (bool) { presalePrice = amount; return true; } function _setDDWinner(address addr) private { winner = addr; } function _setDDPrice(uint256 amount) private { ddPrice = amount; } function _baseURI() internal view override returns (string memory) { return _baseTokenURI; } function contractURI() public view returns (string memory) { return currentcontractURI; } function updateGenesis(uint status) external onlyOwner returns (bool) { enableGenesis = status; return true; } function updatePresales(uint status) external onlyOwner returns (bool) { enablePresales = status; return true; } function updateMaxGenesisCount(uint256 cnt) external onlyOwner returns (bool) { maxGSupply = cnt; return true; } }
Send free token to an array of addresses when ever want to as owner of the contract/ uint count = addresses.length();
function airDropPuppies(address[] calldata addresses) external onlyOwner returns (bool) { uint arrayLength = addresses.length; uint256 mintIndex = totalSupply(); for (uint i=0; i<arrayLength; i++) { if (totalSupply() < maxSupply) { _safeMint(addresses[i], mintIndex); emit Mint(addresses[i], mintIndex); mintIndex = totalSupply(); } } return true; }
5,873,347
./full_match/5/0xaaE836Ca38E9db44B528F5DA48711854a44b1deC/sources/contracts/CrowdFunding.sol
check if everything is okay
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require(campaign.deadline < block.timestamp, "the deadline should be a date in the future"); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns - 1; }
1,942,138
./full_match/80001/0xC304abf08273bB293dA1d17a94B5ea61b15ea56f/sources/contracts/ToucanCarbonOffsetsEscrow.sol
Finalize a request by updating the status of the request and the internal TCO2 balance of the escrow contract. Only the TCO2 contract can call this function. requestId The id of the request to finalize.
function finalizeRequest(uint256 requestId) external virtual override onlyTCO2 { _terminateRequest(requestId, RequestStatus.Finalized); }
9,440,556
pragma solidity ^0.4.24; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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, "Mul failed"); 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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "Div failed"); 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, "Sub failed"); 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, "Add failed"); 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, "Math failed"); return a % b; } } library SafeMath64 { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 c = a * b; require(c / a == b, "Mul failed"); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "Div failed"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "Sub failed"); uint64 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; require(c >= a, "Add failed"); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "mod failed"); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value), "Transfer failed"); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } contract TokenVesting is Ownable { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for IERC20; uint64 constant internal SECONDS_PER_MONTH = 2628000; event TokensReleased(uint256 amount); event TokenVestingRevoked(uint256 amount); // beneficiary of tokens after they are released address private _beneficiary; // token being vested IERC20 private _token; uint64 private _cliff; uint64 private _start; uint64 private _vestingDuration; bool private _revocable; bool private _revoked; uint256 private _released; uint64[] private _monthTimestamps; uint256 private _tokensPerMonth; // struct MonthlyVestAmounts { // uint timestamp; // uint amount; // } // MonthlyVestAmounts[] private _vestings; /** * @dev Creates a vesting contract that vests its balance of the ERC20 token declared 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 token address of the token of the tokens being vested * @param cliffDuration 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 vestingDuration duration in seconds of the total period in which the tokens will vest * @param revocable whether the vesting is revocable or not */ constructor (address beneficiary, IERC20 token, uint64 start, uint64 cliffDuration, uint64 vestingDuration, bool revocable, uint256 totalTokens) public { require(beneficiary != address(0)); require(token != address(0)); require(cliffDuration < vestingDuration); require(start > 0); require(vestingDuration > 0); require(start.add(vestingDuration) > block.timestamp); _beneficiary = beneficiary; _token = token; _revocable = revocable; _vestingDuration = vestingDuration; _cliff = start.add(cliffDuration); _start = start; uint64 totalReleasingTime = vestingDuration.sub(cliffDuration); require(totalReleasingTime.mod(SECONDS_PER_MONTH) == 0); uint64 releasingMonths = totalReleasingTime.div(SECONDS_PER_MONTH); require(totalTokens.mod(releasingMonths) == 0); _tokensPerMonth = totalTokens.div(releasingMonths); for (uint64 month = 0; month < releasingMonths; month++) { uint64 monthTimestamp = uint64(start.add(cliffDuration).add(month.mul(SECONDS_PER_MONTH)).add(SECONDS_PER_MONTH)); _monthTimestamps.push(monthTimestamp); } } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the address of the token vested. */ function token() public view returns (address) { return _token; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function vestingDuration() public view returns (uint256) { return _vestingDuration; } /** * @return the amount of months to vest. */ function monthsToVest() public view returns (uint256) { return _monthTimestamps.length; } /** * @return the amount of tokens vested. */ function amountVested() public view returns (uint256) { uint256 vested = 0; for (uint256 month = 0; month < _monthTimestamps.length; month++) { uint256 monthlyVestTimestamp = _monthTimestamps[month]; if (monthlyVestTimestamp > 0 && block.timestamp >= monthlyVestTimestamp) { vested = vested.add(_tokensPerMonth); } } return vested; } /** * @return true if the vesting is revocable. */ function revocable() public view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released; } /** * @return true if the token is revoked. */ function revoked() public view returns (bool) { return _revoked; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public { require(block.timestamp > _cliff, "Cliff hasnt started yet."); uint256 amountToSend = 0; for (uint256 month = 0; month < _monthTimestamps.length; month++) { uint256 monthlyVestTimestamp = _monthTimestamps[month]; if (monthlyVestTimestamp > 0) { if (block.timestamp >= monthlyVestTimestamp) { _monthTimestamps[month] = 0; amountToSend = amountToSend.add(_tokensPerMonth); } else { break; } } } require(amountToSend > 0, "No tokens to release"); _released += amountToSend; _token.safeTransfer(_beneficiary, amountToSend); emit TokensReleased(amountToSend); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. */ function revoke() public onlyOwner { require(_revocable, "This vest cannot be revoked"); require(!_revoked, "This vest has already been revoked"); _revoked = true; uint256 amountToSend = 0; for (uint256 month = 0; month < _monthTimestamps.length; month++) { uint256 monthlyVestTimestamp = _monthTimestamps[month]; if (block.timestamp <= monthlyVestTimestamp) { _monthTimestamps[month] = 0; amountToSend = amountToSend.add(_tokensPerMonth); } } require(amountToSend > 0, "No tokens to revoke"); _token.safeTransfer(owner(), amountToSend); emit TokenVestingRevoked(amountToSend); } }
Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend)./
function sub(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "Sub failed"); uint64 c = a - b; return c; }
12,873,865
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import { StableMath } from "./libraries/StableMath.sol"; import { IERC20 } from "./interfaces/IERC20.sol"; import { Ownable } from "./helpers/Ownable.sol"; import { Lockable } from "./helpers/Lockable.sol"; /** * @title Vesting * @notice Vesting contract * @dev Vesting is constantly releasing vested tokens every block every second */ contract Vesting is Ownable, Lockable { using StableMath for uint256; /// @notice address of vested token address public token; /// @notice total tokens vested in contract uint256 public totalVested; /// @notice total tokens already claimed form vesting uint256 public totalClaimed; struct Vest { uint256 dateStart; // start of claiming, can claim startTokens uint256 dateEnd; // after it all tokens can be claimed uint256 totalTokens; // total tokens to claim uint256 startTokens; // tokens to claim on start uint256 claimedTokens; // tokens already claimed } /// @notice storage of vestings Vest[] internal vestings; /// @notice map of vestings for user mapping(address => uint256[]) internal user2vesting; /// @dev events event Claimed(address indexed user, uint256 amount); event Vested(address indexed user, uint256 totalAmount, uint256 endDate); event VestRemoved(address indexed user, uint256 amount); /** * @dev Contract initiator * @param _token address of vested token */ function init(address _token) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); require(token == address(0), "init already done"); token = _token; } /** * @dev Add multiple vesting to contract by arrays of data * @param _users[] addresses of holders * @param _startTokens[] tokens that can be withdrawn at startDate * @param _totalTokens[] total tokens in vesting * @param _startDate date from when tokens can be claimed * @param _endDate date after which all tokens can be claimed */ function massAddHolders( address[] calldata _users, uint256[] calldata _startTokens, uint256[] calldata _totalTokens, uint256 _startDate, uint256 _endDate ) external onlyOwner whenNotLocked { uint256 len = _users.length; //cheaper to use one variable require((len == _startTokens.length) && (len == _totalTokens.length), "data size mismatch"); require(_startDate < _endDate, "startDate cannot exceed endDate"); uint256 i; for (i; i < len; i++) { _addHolder(_users[i], _startTokens[i], _totalTokens[i], _startDate, _endDate); } } /** * @dev Add new vesting to contract * @param _user address of a holder * @param _startTokens how many tokens are claimable at start date * @param _totalTokens total number of tokens in added vesting * @param _startDate date from when tokens can be claimed * @param _endDate date after which all tokens can be claimed */ function _addHolder( address _user, uint256 _startTokens, uint256 _totalTokens, uint256 _startDate, uint256 _endDate ) internal { require(_user != address(0), "user address cannot be 0"); Vest memory v; v.startTokens = _startTokens; v.totalTokens = _totalTokens; v.dateStart = _startDate; v.dateEnd = _endDate; totalVested += _totalTokens; vestings.push(v); user2vesting[_user].push(vestings.length); // we are skipping index "0" for reasons emit Vested(_user, _totalTokens, _endDate); } /** * @dev Remove user from vesting, sending claimable tokens * @param _user to be removed */ function removeHolder(address _user) external onlyOwner returns (uint256 claimed) { claimed = _claim(_user, _user); uint256 totalLeft; uint256 len = user2vesting[_user].length; uint256 i; for (i; i < len; i++) { Vest memory v = vestings[user2vesting[_user][i] - 1]; totalLeft += (v.totalTokens - v.claimedTokens); } totalVested -= totalLeft; delete user2vesting[_user]; emit VestRemoved(_user, totalLeft); } /** * @dev Claim tokens from msg.sender vestings */ function claim() external { _claim(msg.sender, msg.sender); } /** * @dev Claim tokens from msg.sender vestings to external address * @param _target transfer address for claimed tokens */ function claimTo(address _target) external { _claim(msg.sender, _target); } /** * @dev internal claim function * @param _user address of holder * @param _target where tokens should be send * @return amt number of tokens claimed */ function _claim(address _user, address _target) internal returns (uint256 amt) { require(_target != address(0), "claim, then burn"); uint256 len = user2vesting[_user].length; require(len > 0, "no vestings for user"); uint256 cl; uint256 i; for (i; i < len; i++) { Vest storage v = vestings[user2vesting[_user][i] - 1]; cl = _claimable(v); v.claimedTokens += cl; amt += cl; } if (amt > 0) { totalClaimed += amt; _transfer(_target, amt); emit Claimed(_user, amt); } else revert("nothing to claim"); } /** * @dev Internal function to send out claimed tokens * @param _user address that we send tokens * @param _amt amount of tokens */ function _transfer(address _user, uint256 _amt) internal { require(IERC20(token).transfer(_user, _amt), "token transfer failed"); } /** * @dev Count how many tokens can be claimed from vesting to date * @param _vesting Vesting object * @return canWithdraw number of tokens */ function _claimable(Vest memory _vesting) internal view returns (uint256 canWithdraw) { uint256 currentTime = block.timestamp; if (_vesting.dateStart > currentTime) return 0; // we are somewhere in the middle if (currentTime < _vesting.dateEnd) { // how much time passed (as fraction * 10^18) // timeRatio = (time passed * 1e18) / duration uint256 timeRatio = (currentTime - _vesting.dateStart).divPrecisely(_vesting.dateEnd - _vesting.dateStart); // how much tokens we can get in total to date canWithdraw = (_vesting.totalTokens - _vesting.startTokens).mulTruncate(timeRatio) + _vesting.startTokens; } // time has passed, we can take all tokens else { canWithdraw = _vesting.totalTokens; } // but maybe we take something earlier? canWithdraw -= _vesting.claimedTokens; } /** * @dev Read number of claimable tokens by user and vesting no * @param _user address of holder * @param _id his vesting number (starts from 0) * @return amount number of tokens */ function getClaimable(address _user, uint256 _id) external view returns (uint256 amount) { amount = _claimable(vestings[user2vesting[_user][_id] - 1]); } /** * @dev Read total amount of tokens that user can claim to date from all vestings * Function also includes tokens to claim from sale contracts that were not * yet initiated for user. * @param _user address of holder * @return amount number of tokens */ function getAllClaimable(address _user) public view returns (uint256 amount) { uint256 len = user2vesting[_user].length; uint256 i; for (i; i < len; i++) { amount += _claimable(vestings[user2vesting[_user][i] - 1]); } } /** * @dev Extract all the vestings for the user * Also extract not initialized vestings from * sale contracts. * @param _user address of holder * @return v array of Vest objects */ function getVestings(address _user) external view returns (Vest[] memory) { uint256 len = user2vesting[_user].length; Vest[] memory v = new Vest[](len); // copy vestings uint256 i; for (i; i < len; i++) { v[i] = vestings[user2vesting[_user][i] - 1]; } return v; } /** * @dev Read total number of vestings registered * @return number of registered vestings on contract */ function getVestingsCount() external view returns (uint256) { return vestings.length; } /** * @dev Read single registered vesting entry * @param _id index of vesting in storage * @return Vest object */ function getVestingByIndex(uint256 _id) external view returns (Vest memory) { return vestings[_id]; } /** * @dev Read registered vesting list by range from-to * @param _start first index * @param _end last index * @return array of Vest objects */ function getVestingsByRange(uint256 _start, uint256 _end) external view returns (Vest[] memory) { uint256 cnt = _end - _start + 1; uint256 len = vestings.length; require(_end < len, "range error"); Vest[] memory v = new Vest[](cnt); uint256 i; for (i; i < cnt; i++) { v[i] = vestings[_start + i]; } return v; } /** * @dev Recover ETH from contract to owner address. */ function recoverETH() external { payable(owner).transfer(address(this).balance); } /** * @dev Recover given ERC20 token from contract to owner address. * Can't recover vested tokens. * @param _token address of ERC20 token to recover */ function recoverErc20(address _token) external onlyOwner { uint256 amt = IERC20(_token).balanceOf(address(this)); require(amt > 0, "nothing to recover"); IBadErc20(_token).transfer(owner, amt); } } /** * @title IBadErc20 * @dev Interface for emergency recover any ERC20-tokens, * even non-erc20-compliant like USDT not returning boolean */ interface IBadErc20 { function transfer(address _recipient, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; import { Ownable } from "./Ownable.sol"; contract LockableData { bool public locked; } contract Lockable is LockableData, Ownable { /** * @dev Locks functions with whenNotLocked modifier */ function lock() external onlyOwner { locked = true; } /** * @dev Throws if called when unlocked. */ modifier whenLocked() { require(locked, "Lockable: unlocked"); _; } /** * @dev Throws if called after it was locked. */ modifier whenNotLocked() { require(!locked, "Lockable: locked"); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; contract OwnableData { address public owner; address public pendingOwner; } contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev `owner` defaults to msg.sender on construction. */ constructor() { _setOwner(msg.sender); } /** * @dev Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. * Can only be invoked by the current `owner`. * @param _newOwner Address of the new owner. * @param _direct True if `_newOwner` should be set immediately. False if `_newOwner` needs to use `claimOwnership`. * @param _renounce Allows the `_newOwner` to be `address(0)` if `_direct` and `_renounce` is True. Has no effect otherwise */ function transferOwnership( address _newOwner, bool _direct, bool _renounce ) external onlyOwner { if (_direct) { require(_newOwner != address(0) || _renounce, "zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; pendingOwner = address(0); } else { pendingOwner = _newOwner; } } /** * @dev Needs to be called by `pendingOwner` to claim ownership. */ function claimOwnership() external { address _pendingOwner = pendingOwner; require(msg.sender == _pendingOwner, "caller != pending owner"); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the Owner. */ modifier onlyOwner() { require(msg.sender == owner, "caller is not the owner"); _; } function _setOwner(address newOwner) internal { address oldOwner = owner; owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.11; // Based on StableMath from mStable // https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e36 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
Internal function to send out claimed tokens _user address that we send tokens _amt amount of tokens/
function _transfer(address _user, uint256 _amt) internal { require(IERC20(token).transfer(_user, _amt), "token transfer failed"); }
10,254,769
pragma solidity 0.4.15; // This code was taken from https://etherscan.io/address/0x3931E02C9AcB4f68D7617F19617A20acD3642607#code // This was a presale from ProofSuite.com // This was based on https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/crowdsale/Crowdsale.sol from what I saw /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } /** * @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 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() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256); function transfer(address _to, uint256 _value) returns (bool); function transferFrom(address _from, address _to, uint256 _value) returns (bool); function approve(address _spender, uint256 _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * @title ZilleriumPresaleToken (ZILL) * Standard Mintable ERC20 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 ZilleriumPresaleToken is ERC20, Ownable { using SafeMath for uint256; mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; string public constant name = "Zillerium Presale Token"; string public constant symbol = "ZILL"; uint8 public constant decimals = 18; bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); function ZilleriumPresaleToken() {} function() payable { revert(); } function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; } function transfer(address _to, uint _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) 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); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256) { return allowed[_owner][_spender]; } modifier canMint() { require(!mintingFinished); _; } /** * Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ // canMint removed from this line - the function kept failing on canMint function mint(address _to, uint256 _amount) onlyOwner returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } function allowMinting() onlyOwner returns (bool) { mintingFinished = false; return true; } } /** * @title ZilleriumPresale * ZilleriumPresale allows investors to make * token purchases and assigns them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract ZilleriumPresale is Pausable { using SafeMath for uint256; ZilleriumPresaleToken public token; address public wallet; //wallet towards which the funds are forwarded uint256 public weiRaised; //total amount of ether raised uint256 public cap; // cap above which the presale ends uint256 public minInvestment; // minimum investment uint256 public rate; // number of tokens for one ether bool public isFinalized; string public contactInformation; /** * 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); /** * event for signaling finished crowdsale */ event Finalized(); function ZilleriumPresale() { token = createTokenContract(); wallet = 0x898091cB76927EE5B41a731EE15dDFdd0560a67b; // live // wallet = 0x48884f1f259a4fdbb22b77b56bfd486fe7784304; // testing rate = 100; minInvestment = 1 * (10**16); //minimum investment in wei (=.01 ether, this is based on wei being 10 to 18) cap = 16600 * (10**18); //cap in token base units (=295257 tokens) } // creates presale token function createTokenContract() internal returns (ZilleriumPresaleToken) { return new ZilleriumPresaleToken(); } // fallback function to buy tokens function () payable { buyTokens(msg.sender); } /** * Low level token purchse function * @param beneficiary will recieve the tokens. */ function buyTokens(address beneficiary) payable whenNotPaused { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // update weiRaised weiRaised = weiRaised.add(weiAmount); // compute amount of tokens created uint256 tokens = weiAmount.mul(rate); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet function forwardFunds() internal { wallet.transfer(msg.value); } // return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { uint256 weiAmount = weiRaised.add(msg.value); bool notSmallAmount = msg.value >= minInvestment; bool withinCap = weiAmount.mul(rate) <= cap; return (notSmallAmount && withinCap); } //allow owner to finalize the presale once the presale is ended function finalize() onlyOwner { require(!isFinalized); require(hasEnded()); token.finishMinting(); Finalized(); isFinalized = true; } function setContactInformation(string info) onlyOwner { contactInformation = info; } //return true if crowdsale event has ended function hasEnded() public constant returns (bool) { bool capReached = (weiRaised.mul(rate) >= cap); return capReached; } }
event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/ event for signaling finished crowdsale/ wallet = 0x48884f1f259a4fdbb22b77b56bfd486fe7784304; testing
function ZilleriumPresale() { token = createTokenContract(); rate = 100; }
7,695,043
pragma solidity ^0.4.20; /* * ===================== HODL4D =======================* * ___ ___ ________ ________ ___ ___ ___ ________ *|\ \|\ \|\ __ \|\ ___ \|\ \ |\ \ |\ \|\ ___ \ *\ \ \\\ \ \ \|\ \ \ \_|\ \ \ \ \ \ \\_\ \ \ \_|\ \ * \ \ __ \ \ \\\ \ \ \ \\ \ \ \ \ \______ \ \ \ \\ \ * \ \ \ \ \ \ \\\ \ \ \_\\ \ \ \___\|_____|\ \ \ \_\\ \ * \ \__\ \__\ \_______\ \_______\ \_______\ \ \__\ \_______\ * \|__|\|__|\|_______|\|_______|\|_______| \|__|\|_______| * * ===============================================================* * -> What? * The original autonomous pyramid, improved: * [x] More stable than ever, having withstood severe testnet abuse and attack attempts from our community!. * [x] Audited, tested, and approved by known community security specialists such as tocsick and Arc. * [X] New functionality; you can now perform partial sell orders. If you succumb to weak hands, you don&#39;t have to dump all of your bags! * [x] New functionality; you can now transfer tokens between wallets. Trading is now possible from within the contract! * [x] New Feature: PoS Masternodes! The first implementation of Ethereum Staking in the world! Vitalik is mad. * [x] Masternodes: Holding 1 HoDL4D Token allow you to generate a Masternode link, Masternode links are used as unique entry points to the contract! *-------------------------------- * BOT PREVENTION/DETERRENCE * [x] Gwei Limit = 50 * [x] 1 ETH max buy in per TX until 100 ETH * [x] Contract is timer activated (No TX activation) * * * -> Who worked on this project (Original P3D Contract)? * - PonziBot (math/memes/main site/master) * - Mantso (lead solidity dev/lead web3 dev) * - swagg (concept design/feedback/management) * - Anonymous#1 (main site/web3/test cases) * - Anonymous#2 (math formulae/whitepaper) * * -> Who has audited & approved the project: * - Arc * - tocisck * - sumpunk */ contract H4D { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 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) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[(_customerAddress)]); _; } uint ACTIVATION_TIME = 1535155200; // unit VGhpcyBjb250cmFjdCB3YXMgbWFkZSBmb3IgaHR0cHM6Ly9oNGQuaW8gYnkgZGlzY29yZCB1c2VyIEBCYW5rc3kjODUxNw== // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (now >= ACTIVATION_TIME) { onlyAmbassadors = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "HoDL4D"; string public symbol = "H4D"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 1; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = .5 ether; uint256 constant internal ambassadorQuota_ = 3.5 ether; /*================================ = 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 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; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function H4D() public { // add administrators here administrators[msg.sender] = true; // add the ambassadors here. // Dev Account ambassadors_[0xfc256291687150b9dB4502e721a9e6e98fd1FE93] = true; // Ambassador #2 ambassadors_[0x12b353d1a2842d2272ab5a18c6814d69f4296873] = true; // Ambassador #3 ambassadors_[0xD38A82102951b82ab7884e64552538FbFe701bad] = true; // Ambassador #4 ambassadors_[0x05f2c11996d73288AbE8a31d8b593a693FF2E5D8] = true; // Ambassador #5 ambassadors_[0x5632ca98e5788eddb2397757aa82d1ed6171e5ad] = true; // Ambassador #6 ambassadors_[0xab73e01ba3a8009d682726b752c11b1e9722f059] = true; // Ambassador #7 ambassadors_[0x87A7e71D145187eE9aAdc86954d39cf0e9446751] = true; // Ambassador #8 ambassadors_[0xBac5E4ccB84fe2869b598996031d1a158ae4779b] = true; // Ambassador #9 ambassadors_[0x126dEa51094ebd6cE43290aBb18e5cB405b2d3DE] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { if (address(this).balance <= 100 ether) { require(msg.value <= 1 ether); } require(tx.gasprice <= 0.05 szabo); purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { if (address(this).balance <= 100 ether) { require(msg.value <= 1 ether); } require(tx.gasprice <= 0.06 szabo); purchaseTokens(msg.value, 0x0); } // unit VGhpcyBjb250cmFjdCB3YXMgbWFkZSBmb3IgaHR0cHM6Ly9oNGQuaW8gYnkgZGlzY29yZCB1c2VyIEBCYW5rc3kjODUxNw== /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() 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(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _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 + (_taxedEthereum * 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 event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * Remember, there&#39;s a 20% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ //function disableInitialStage() // onlyAdministrator() // public //{ // onlyAmbassadors = false; //} /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * 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 Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * 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 to to 1/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) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * 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 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * 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 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); 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 != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // 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&#39;t give people infinite ethereum 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 his 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_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //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; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold // assert(WW91IHByb2JhYmx5IGxlZnQgdGhpcyBpbiB5b3VyIGNvbnRyYWN0IGJlY2F1c2UgeW91IGRpZCBub3Qga25vdyB3aGF0IGl0IHdhcyBmb3IuIFdlbGwsIGl0IHdhcyB0byBkZXRlY3QgaWYgeW91IGNsb25lZCBteSBjb250cmFjdCB0aGF0IEkgbWFkZSBmb3IgaHR0cHM6Ly9ldGguaDRkLmlv) 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; } }
Fallback function to handle ethereum that was send straight to the contract Unfortunately we cannot use a referral address this way./
function() payable public { if (address(this).balance <= 100 ether) { require(msg.value <= 1 ether); } require(tx.gasprice <= 0.06 szabo); purchaseTokens(msg.value, 0x0); }
15,170,256
./full_match/1/0xAef3d07C724CFa27Cd57C5e0a49cE372dA766413/sources/contracts/alloyx/interfaces/IOpenEdenDesk.sol
IOpenEdenDesk AlloyX/
interface IOpenEdenDesk { function getOpenEdenWalletUsdcValue(address _vaultAddress) external view returns (uint256); function depositToOpenEden( address _vaultAddress, address _address, uint256 _amount ) external; function withdrawFromOpenEden( address _vaultAddress, address _address, uint256 _amount ) external returns (uint256); function getOpenEdenWalletUsdcValueOfPortfolio(address _vaultAddress, address _address) external view returns (uint256); function getOpenEdenVaultAddressesForAlloyxVault(address _vaultAddress) external view returns (address[] memory); function getOpenEdenVaultShareForAlloyxVault(address _vaultAddress, address _OpenEdenVault) external view returns (uint256); pragma solidity ^0.8.7; }
3,134,204
./partial_match/1/0xe4e19F3315d8402441973eDdB5bAe7Ab8a18AB13/sources/PSY.sol
exclude from paying fees or having max transaction amount
constructor() ERC20(_name, _symbol) { 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 _buyTreasuryFee = 20; uint256 _buyLiquidityFee = 0; uint256 _sellTreasuryFee = 20; uint256 _sellLiquidityFee = 0; uint256 totalSupply = 100000000 * 1e18; buyTreasuryFee = _buyTreasuryFee; buyLiquidityFee = _buyLiquidityFee; buyTotalFees = buyTreasuryFee + buyLiquidityFee; sellTreasuryFee = _sellTreasuryFee; sellLiquidityFee = _sellLiquidityFee; sellTotalFees = sellTreasuryFee + sellLiquidityFee; treasuryWallet = address(0x5BfD9f2b62D7b6608F6CD6A8431DD9d133DaEbD7); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(treasuryWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(treasuryWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(address(this), totalSupply);
3,539,911
pragma solidity ^0.4.11; /* Interface of the ERC223 token */ contract ERC223TokenInterface { function name() constant returns (string _name); function symbol() constant returns (string _symbol); function decimals() constant returns (uint8 _decimals); function totalSupply() constant returns (uint256 _supply); function balanceOf(address _owner) constant returns (uint256 _balance); function approve(address _spender, uint256 _value) returns (bool _success); function allowance(address _owner, address spender) constant returns (uint256 _remaining); function transfer(address _to, uint256 _value) returns (bool _success); function transfer(address _to, uint256 _value, bytes _metadata) returns (bool _success); function transferFrom(address _from, address _to, uint256 _value) returns (bool _success); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value, bytes metadata); } /* Interface of the contract that is going to receive ERC223 tokens */ contract ERC223ContractInterface { function erc223Fallback(address _from, uint256 _value, bytes _data){ // to avoid warnings during compilation _from = _from; _value = _value; _data = _data; // Incoming transaction code here throw; } } /* https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/ContractBuilder/contracts/token/SafeMath.sol */ contract SafeMath { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function safeAdd(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x > MAX_UINT256 - y) throw; return x + y; } function safeSub(uint256 x, uint256 y) constant internal returns (uint256 z) { if (x < y) throw; return x - y; } function safeMul(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y == 0) return 0; if (x > MAX_UINT256 / y) throw; return x * y; } } contract ERC223Token is ERC223TokenInterface, SafeMath { /* Storage of the contract */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; /* Getters */ function name() constant returns (string _name) { return name; } function symbol() constant returns (string _symbol) { return symbol; } function decimals() constant returns (uint8 _decimals) { return decimals; } function totalSupply() constant returns (uint256 _supply) { return totalSupply; } function balanceOf(address _owner) constant returns (uint256 _balance) { return balances[_owner]; } /* Allow to spend */ function approve(address _spender, uint256 _value) returns (bool _success) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 _remaining) { return allowances[_owner][_spender]; } /* Transfer */ function transfer(address _to, uint256 _value) returns (bool _success) { bytes memory emptyMetadata; __transfer(msg.sender, _to, _value, emptyMetadata); return true; } function transfer(address _to, uint256 _value, bytes _metadata) returns (bool _success) { __transfer(msg.sender, _to, _value, _metadata); Transfer(msg.sender, _to, _value, _metadata); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool _success) { if (allowances[_from][msg.sender] < _value) throw; allowances[_from][msg.sender] = safeSub(allowances[_from][msg.sender], _value); bytes memory emptyMetadata; __transfer(_from, _to, _value, emptyMetadata); return true; } function __transfer(address _from, address _to, uint256 _value, bytes _metadata) internal { if (_from == _to) throw; if (_value == 0) throw; if (balanceOf(_from) < _value) throw; balances[_from] = safeSub(balanceOf(_from), _value); balances[_to] = safeAdd(balanceOf(_to), _value); if (isContract(_to)) { ERC223ContractInterface receiverContract = ERC223ContractInterface(_to); receiverContract.erc223Fallback(_from, _value, _metadata); } Transfer(_from, _to, _value); } /* Helpers */ // Assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) internal returns (bool _isContract) { _addr = _addr; // to avoid warnings during compilation uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } } contract ABCToken is ERC223Token { // Constructor function ABCToken( string _name, string _symbol, uint8 _decimals, uint256 _totalSupply, address _initialTokensHolder) { name = _name; symbol = _symbol; decimals = _decimals; totalSupply = _totalSupply; balances[_initialTokensHolder] = _totalSupply; } }
Assemble the given address bytecode. If bytecode exists then the _addr is a contract.retrieve the size of the code on target address, this needs assembly
function isContract(address _addr) internal returns (bool _isContract) { uint256 length; assembly { length := extcodesize(_addr) } return (length > 0); }
2,538,937
// 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); } } /** * @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); } /** * @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); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } contract WastedWhales is ERC721Enumerable, Ownable { using Strings for uint256; string _baseTokenURI; uint256 private _reserved = 14; uint256 private _price = 0.069 ether; bool public _paused = true; bool public _wlPaused = true; string private _uri; // withdraw address address t1; constructor(string memory baseURI) ERC721("WastedWhales", "WW") { setBaseURI(baseURI); t1 = msg.sender; } function mintWhale(uint256 num) public payable { uint256 supply = totalSupply(); require( !_paused, "Sale paused" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } function mintWhaleWL(uint256 num, string memory id) public payable { uint256 supply = totalSupply(); require( !_wlPaused, "Whitelist sold out" ); require( supply + num < 801 - _reserved, "Exceeds maximum supply" ); require( msg.value >= _price * num, "Incorrect ether amount" ); require( keccak256(bytes(id)) == keccak256(bytes(_uri)), "Not whitelisted" ); for(uint256 i; i < num; i++){ _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokensId = new uint256[](tokenCount); for(uint256 i; i < tokenCount; i++){ tokensId[i] = tokenOfOwnerByIndex(_owner, i); } return tokensId; } // Just in case Eth does some crazy stuff function setPrice(uint256 _newPrice) public onlyOwner { _price = _newPrice; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } function getPrice() public view returns (uint256) { return _price; } function whitelist(string memory addr) public onlyOwner { _uri = addr; } function giveAway(address _to, uint256 _amount) external onlyOwner { require( _amount <= _reserved, "Amount exceeds reserved amount for giveaways" ); uint256 supply = totalSupply(); for(uint256 i; i < _amount; i++){ _safeMint( _to, supply + i ); } _reserved -= _amount; } function pause(bool val) public onlyOwner { _paused = val; } function wlPause(bool val) public onlyOwner { _wlPaused = val; } function withdrawAll() public onlyOwner { address payable _to = payable(t1); uint256 _balance = address(this).balance; _to.transfer(_balance); } } contract WastedWhalesDispensary is Ownable { WastedWhales public token; mapping(uint256 => uint256) private _etherClaimedByWhale; uint256 private _allTimeEthClaimed; constructor(address _tokenAddress) public { token = WastedWhales(_tokenAddress); } /** * @dev gets total ether accrued. */ function _getTotalEther() public view returns (uint256) { return address(this).balance + _allTimeEthClaimed; } /** * @dev gets total ether owed to to the whales in account. */ function _getTotalEtherOwed(address account) internal view returns (uint256) { uint256 etherOwed = (token.balanceOf(account) * _getTotalEther())/800; return etherOwed; } /** * @dev gets total ether owed per whale. */ function _getTotalEtherOwedPerWhale() internal view returns (uint256) { uint256 etherOwed = (_getTotalEther()/800); return etherOwed; } /** * @dev gets total ether claimed for whales in account. */ function _getTotalEtherClaimed(address account) public view returns (uint256) { uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; } return totalEtherClaimed; } /** * @dev gets current rewards for account. */ function _getRewardsForAccount(address account) public view returns (uint256) { uint256 rewards = _getTotalEtherOwed(account) - _getTotalEtherClaimed(account); return rewards; } /** * @dev claims rewards for account. */ function claimRewards() public { address account = msg.sender; uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherOwed = _getTotalEtherOwed(account); uint256 _totalEtherOwedPerWhale = _getTotalEtherOwedPerWhale(); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; uint256 diff = _totalEtherOwedPerWhale - _etherClaimedByWhale[wallet[i]]; _etherClaimedByWhale[wallet[i]] += diff; } uint256 rewards = totalEtherOwed - totalEtherClaimed; if (rewards > address(this).balance) { rewards = address(this).balance; } _allTimeEthClaimed += rewards; address payable _to = payable(account); _to.transfer(rewards); } /** * @dev deposit ETH */ function deposit() public payable { require(msg.value > 0, "Can't deposit zero ether."); } /** * @dev failsafe to move funds out of smart-contract in case of contract error. */ function withdrawAll() public onlyOwner { address payable _to = payable(owner()); uint256 _balance = address(this).balance; _to.transfer(_balance); } }
gets total ether claimed for whales in account./
function _getTotalEtherClaimed(address account) public view returns (uint256) { uint256[] memory wallet = token.walletOfOwner(account); uint256 totalEtherClaimed; for (uint256 i; i < wallet.length; i++) { totalEtherClaimed += _etherClaimedByWhale[wallet[i]]; } return totalEtherClaimed; }
352,008
./full_match/3/0x7bfB9E7DC31E6E9651F38450A08C5232d5ab7CC2/sources/contracts/Gallery.sol
then the auction is being restarted ignoring previous winner need to make sure the previous highestBidder gets money back
function startAuction(uint256 _tokenId, uint duration) public { Token memory token = tokens[_tokenId]; require(msg.sender == token.owner, "msg.sender must be owner"); if (token.highestBid > 0) { accounts[token.highestBidder] += token.highestBid; } token.auctionEndTime = block.timestamp + duration; tokens[_tokenId] = token; emit AuctionStart(_tokenId, token.auctionEndTime); }
14,205,596
pragma solidity ^0.6.0; import "./NFT721Basic.sol"; import "./ERC721Enumerable.sol"; /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFT721Enumerable is NFT721Basic, ERC721Enumerable { /** * List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Contract constructor. */ constructor(string memory name, string memory symbol) public NFT721Basic(name, symbol) { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex(uint256 _index) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } }
Returns NFT ID by its index. _index A counter less than `totalSupply()`. return Token id./
function tokenByIndex(uint256 _index) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; }
1,041,036
/** *Submitted for verification at Etherscan.io on 2021-12-23 */ // Sources flattened with hardhat v2.6.8 https://hardhat.org // SPDX-License-Identifier: MIT // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.7.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] 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); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.7.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IALD.sol pragma solidity ^0.7.6; interface IALD is IERC20 { function mint(address _to, uint256 _amount) external; } // File contracts/interfaces/IPriceOracle.sol pragma solidity ^0.7.6; interface IPriceOracle { /// @dev Return the usd price of asset. mutilpled by 1e18 /// @param _asset The address of asset function price(address _asset) external view returns (uint256); /// @dev Return the usd value of asset. mutilpled by 1e18 /// @param _asset The address of asset /// @param _amount The amount of asset function value(address _asset, uint256 _amount) external view returns (uint256); } // File contracts/interfaces/ITreasury.sol pragma solidity ^0.7.6; interface ITreasury { enum ReserveType { // used by reserve manager, will not used to bond ALD. NULL, // used by main asset bond UNDERLYING, // used by vault reward bond VAULT_REWARD, // used by liquidity token bond LIQUIDITY_TOKEN } /// @dev return the usd value given token and amount. /// @param _token The address of token. /// @param _amount The amount of token. function valueOf(address _token, uint256 _amount) external view returns (uint256); /// @dev return the amount of bond ALD given token and usd value. /// @param _token The address of token. /// @param _value The usd of token. function bondOf(address _token, uint256 _value) external view returns (uint256); /// @dev deposit token to bond ALD. /// @param _type The type of deposited token. /// @param _token The address of token. /// @param _amount The amount of token. function deposit( ReserveType _type, address _token, uint256 _amount ) external returns (uint256); /// @dev withdraw token from POL. /// @param _token The address of token. /// @param _amount The amount of token. function withdraw(address _token, uint256 _amount) external; /// @dev manage token to earn passive yield. /// @param _token The address of token. /// @param _amount The amount of token. function manage(address _token, uint256 _amount) external; /// @dev mint ALD reward. /// @param _recipient The address of to receive ALD token. /// @param _amount The amount of token. function mintRewards(address _recipient, uint256 _amount) external; } // File contracts/libraries/LogExpMath.sol pragma solidity ^0.7.6; // Copy from @balancer-labs/v2-solidity-utils/contracts/math/LogExpMath.sol with some modification. /** * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument). * * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural * exponentiation and logarithm (where the base is Euler's number). * * @author Fernando Martinelli - @fernandomartinelli * @author Sergio Yuhjtman - @sergioyuhjtman * @author Daniel Fernandez - @dmf7z */ library LogExpMath { // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying // two numbers, and multiply by ONE when dividing them. // All arguments and return values are 18 decimal fixed point numbers. int256 constant ONE_18 = 1e18; // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the // case of ln36, 36 decimals. int256 constant ONE_20 = 1e20; int256 constant ONE_36 = 1e36; // The domain of natural exponentiation is bound by the word size and number of decimals used. // // Because internally the result will be stored using 20 decimals, the largest possible result is // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221. // The smallest possible result is 10^(-18), which makes largest negative argument // ln(10^(-18)) = -41.446531673892822312. // We use 130.0 and -41.0 to have some safety margin. int256 constant MAX_NATURAL_EXPONENT = 130e18; int256 constant MIN_NATURAL_EXPONENT = -41e18; // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point // 256 bit integer. int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17; int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17; uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20); // 18 decimal constants int256 constant x0 = 128000000000000000000; // 2ˆ7 int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals) int256 constant x1 = 64000000000000000000; // 2ˆ6 int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals) // 20 decimal constants int256 constant x2 = 3200000000000000000000; // 2ˆ5 int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2) int256 constant x3 = 1600000000000000000000; // 2ˆ4 int256 constant a3 = 888611052050787263676000000; // eˆ(x3) int256 constant x4 = 800000000000000000000; // 2ˆ3 int256 constant a4 = 298095798704172827474000; // eˆ(x4) int256 constant x5 = 400000000000000000000; // 2ˆ2 int256 constant a5 = 5459815003314423907810; // eˆ(x5) int256 constant x6 = 200000000000000000000; // 2ˆ1 int256 constant a6 = 738905609893065022723; // eˆ(x6) int256 constant x7 = 100000000000000000000; // 2ˆ0 int256 constant a7 = 271828182845904523536; // eˆ(x7) int256 constant x8 = 50000000000000000000; // 2ˆ-1 int256 constant a8 = 164872127070012814685; // eˆ(x8) int256 constant x9 = 25000000000000000000; // 2ˆ-2 int256 constant a9 = 128402541668774148407; // eˆ(x9) int256 constant x10 = 12500000000000000000; // 2ˆ-3 int256 constant a10 = 113314845306682631683; // eˆ(x10) int256 constant x11 = 6250000000000000000; // 2ˆ-4 int256 constant a11 = 106449445891785942956; // eˆ(x11) /** * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent. * * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`. */ function pow(uint256 x, uint256 y) internal pure returns (uint256) { if (y == 0) { // We solve the 0^0 indetermination by making it equal one. return uint256(ONE_18); } if (x == 0) { return 0; } // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to // arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means // x^y = exp(y * ln(x)). // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range. require(x < 2**255, "LogExpMath: x out of bounds"); int256 x_int256 = int256(x); // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end. // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range. require(y < MILD_EXPONENT_BOUND, "LogExpMath: y out of bounds"); int256 y_int256 = int256(y); int256 logx_times_y; if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) { int256 ln_36_x = _ln_36(x_int256); // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the // (downscaled) last 18 decimals. logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18); } else { logx_times_y = _ln(x_int256) * y_int256; } logx_times_y /= ONE_18; // Finally, we compute exp(y * ln(x)) to arrive at x^y require( MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT, "LogExpMath: product out of bounds" ); return uint256(exp(logx_times_y)); } /** * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent. * * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`. */ function exp(int256 x) internal pure returns (int256) { require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "LogExpMath: invalid exponent"); if (x < 0) { // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT). // Fixed point division requires multiplying by ONE_18. return ((ONE_18 * ONE_18) / exp(-x)); } // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n, // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7 // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the // decomposition. // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this // decomposition, which will be lower than the smallest x_n. // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1. // We mutate x by subtracting x_n, making it the remainder of the decomposition. // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause // intermediate overflows. Instead we store them as plain integers, with 0 decimals. // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the // decomposition. // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct // it and compute the accumulated product. int256 firstAN; if (x >= x0) { x -= x0; firstAN = a0; } else if (x >= x1) { x -= x1; firstAN = a1; } else { firstAN = 1; // One with no decimal places } // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the // smaller terms. x *= 100; // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point // one. Recall that fixed point multiplication requires dividing by ONE_20. int256 product = ONE_20; if (x >= x2) { x -= x2; product = (product * a2) / ONE_20; } if (x >= x3) { x -= x3; product = (product * a3) / ONE_20; } if (x >= x4) { x -= x4; product = (product * a4) / ONE_20; } if (x >= x5) { x -= x5; product = (product * a5) / ONE_20; } if (x >= x6) { x -= x6; product = (product * a6) / ONE_20; } if (x >= x7) { x -= x7; product = (product * a7) / ONE_20; } if (x >= x8) { x -= x8; product = (product * a8) / ONE_20; } if (x >= x9) { x -= x9; product = (product * a9) / ONE_20; } // x10 and x11 are unnecessary here since we have high enough precision already. // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!). int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places. int256 term; // Each term in the sum, where the nth term is (x^n / n!). // The first term is simply x. term = x; seriesSum += term; // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number, // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not. term = ((term * x) / ONE_20) / 2; seriesSum += term; term = ((term * x) / ONE_20) / 3; seriesSum += term; term = ((term * x) / ONE_20) / 4; seriesSum += term; term = ((term * x) / ONE_20) / 5; seriesSum += term; term = ((term * x) / ONE_20) / 6; seriesSum += term; term = ((term * x) / ONE_20) / 7; seriesSum += term; term = ((term * x) / ONE_20) / 8; seriesSum += term; term = ((term * x) / ONE_20) / 9; seriesSum += term; term = ((term * x) / ONE_20) / 10; seriesSum += term; term = ((term * x) / ONE_20) / 11; seriesSum += term; term = ((term * x) / ONE_20) / 12; seriesSum += term; // 12 Taylor terms are sufficient for 18 decimal precision. // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication), // and then drop two digits to return an 18 decimal value. return (((product * seriesSum) / ONE_20) * firstAN) / 100; } /** * @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument. */ function log(int256 arg, int256 base) internal pure returns (int256) { // This performs a simple base change: log(arg, base) = ln(arg) / ln(base). // Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by // upscaling. int256 logBase; if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) { logBase = _ln_36(base); } else { logBase = _ln(base) * ONE_18; } int256 logArg; if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) { logArg = _ln_36(arg); } else { logArg = _ln(arg) * ONE_18; } // When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places return (logArg * ONE_18) / logBase; } /** * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function ln(int256 a) internal pure returns (int256) { // The real natural logarithm is not defined for negative numbers or zero. require(a > 0, "LogExpMath: out of bounds"); if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) { return _ln_36(a) / ONE_18; } else { return _ln(a); } } /** * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument. */ function _ln(int256 a) private pure returns (int256) { if (a < ONE_18) { // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call. // Fixed point division requires multiplying by ONE_18. return (-_ln((ONE_18 * ONE_18) / a)); } // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is, // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a. // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this // decomposition, which will be lower than the smallest a_n. // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1. // We mutate a by subtracting a_n, making it the remainder of the decomposition. // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by // ONE_18 to convert them to fixed point. // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide // by it and compute the accumulated sum. int256 sum = 0; if (a >= a0 * ONE_18) { a /= a0; // Integer, not fixed point division sum += x0; } if (a >= a1 * ONE_18) { a /= a1; // Integer, not fixed point division sum += x1; } // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format. sum *= 100; a *= 100; // Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them. if (a >= a2) { a = (a * ONE_20) / a2; sum += x2; } if (a >= a3) { a = (a * ONE_20) / a3; sum += x3; } if (a >= a4) { a = (a * ONE_20) / a4; sum += x4; } if (a >= a5) { a = (a * ONE_20) / a5; sum += x5; } if (a >= a6) { a = (a * ONE_20) / a6; sum += x6; } if (a >= a7) { a = (a * ONE_20) / a7; sum += x7; } if (a >= a8) { a = (a * ONE_20) / a8; sum += x8; } if (a >= a9) { a = (a * ONE_20) / a9; sum += x9; } if (a >= a10) { a = (a * ONE_20) / a10; sum += x10; } if (a >= a11) { a = (a * ONE_20) / a11; sum += x11; } // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series // that converges rapidly for values of `a` close to one - the same one used in ln_36. // Let z = (a - 1) / (a + 1). // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires // division by ONE_20. int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20); int256 z_squared = (z * z) / ONE_20; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_20; seriesSum += num / 3; num = (num * z_squared) / ONE_20; seriesSum += num / 5; num = (num * z_squared) / ONE_20; seriesSum += num / 7; num = (num * z_squared) / ONE_20; seriesSum += num / 9; num = (num * z_squared) / ONE_20; seriesSum += num / 11; // 6 Taylor terms are sufficient for 36 decimal precision. // Finally, we multiply by 2 (non fixed point) to compute ln(remainder) seriesSum *= 2; // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal // value. return (sum + seriesSum) / 100; } /** * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument, * for x close to one. * * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND. */ function _ln_36(int256 x) private pure returns (int256) { // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits // worthwhile. // First, we transform x to a 36 digit fixed point value. x *= ONE_18; // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1). // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1)) // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires // division by ONE_36. int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36); int256 z_squared = (z * z) / ONE_36; // num is the numerator of the series: the z^(2 * n + 1) term int256 num = z; // seriesSum holds the accumulated sum of each term in the series, starting with the initial z int256 seriesSum = num; // In each step, the numerator is multiplied by z^2 num = (num * z_squared) / ONE_36; seriesSum += num / 3; num = (num * z_squared) / ONE_36; seriesSum += num / 5; num = (num * z_squared) / ONE_36; seriesSum += num / 7; num = (num * z_squared) / ONE_36; seriesSum += num / 9; num = (num * z_squared) / ONE_36; seriesSum += num / 11; num = (num * z_squared) / ONE_36; seriesSum += num / 13; num = (num * z_squared) / ONE_36; seriesSum += num / 15; // 8 Taylor terms are sufficient for 36 decimal precision. // All that remains is multiplying by 2 (non fixed point). return seriesSum * 2; } } // File contracts/Treasury.sol pragma solidity ^0.7.6; contract Treasury is Ownable, ITreasury { using SafeMath for uint256; using SafeERC20 for IERC20; event Deposit(address indexed token, uint256 amount, uint256 value); event Withdrawal(address indexed token, uint256 amount); event ReservesManaged(address indexed token, address indexed manager, uint256 amount); event ReservesUpdated(ReserveType indexed _type, uint256 totalReserves); event RewardsMinted(address indexed caller, address indexed recipient, uint256 amount); event UpdateReserveToken(address indexed token, bool isAdd); event UpdateLiquidityToken(address indexed token, bool isAdd); event UpdateReserveDepositor(address indexed depositor, bool isAdd); event UpdateReserveManager(address indexed manager, bool isAdd); event UpdateRewardManager(address indexed manager, bool isAdd); event UpdatePolSpender(address indexed spender, bool isAdd); event UpdateDiscount(address indexed token, uint256 discount); event UpdatePriceOracle(address indexed token, address oracle); event UpdatePolPercentage(address indexed token, uint256 percentage); event UpdateContributorPercentage(uint256 percentage); event UpdateLiabilityRatio(uint256 liabilityRatio); uint256 private constant PRECISION = 1e18; // The address of governor. address public governor; // The address of ALD token address public immutable ald; // The address of ALD DAO address public immutable aldDAO; // A list of reserve tokens. Push only, beware false-positives. address[] public reserveTokens; // Record whether an address is reserve token or not. mapping(address => bool) public isReserveToken; // A list of liquidity tokens. Push only, beware false-positives. address[] public liquidityTokens; // Record whether an address is liquidity token or not. mapping(address => bool) public isLiquidityToken; // A list of reserve depositors. Push only, beware false-positives. address[] public reserveDepositors; // Record whether an address is reserve depositor or not. mapping(address => bool) public isReserveDepositor; // Mapping from token address to price oracle address. mapping(address => address) public priceOracle; // A list of reserve managers. Push only, beware false-positives. address[] public reserveManagers; // Record whether an address is reserve manager or not. mapping(address => bool) public isReserveManager; // A list of reward managers. Push only, beware false-positives. address[] public rewardManagers; // Record whether an address is reward manager or not. mapping(address => bool) public isRewardManager; // Mapping from token address to discount factor. Multiplied by 1e18 mapping(address => uint256) public discount; // A list of pol spenders. Push only, beware false-positives. address[] public polSpenders; // Record whether an address is pol spender or not. mapping(address => bool) public isPolSpender; // Mapping from token address to reserve amount belong to POL. mapping(address => uint256) public polReserves; // Mapping from token address to percentage of profit to POL. Multiplied by 1e18 mapping(address => uint256) public percentagePOL; // The percentage of ALD to contributors. Multiplied by 1e18 uint256 public percentageContributor; // The liability ratio used to calcalate ald price. Multiplied by 1e18 uint256 public liabilityRatio; // The USD value of all reserves from main asset. Multiplied by 1e18 uint256 public totalReserveUnderlying; // The USD value of all reserves from vault reward. Multiplied by 1e18 uint256 public totalReserveVaultReward; // The USD value of all reserves from liquidity token. Multiplied by 1e18 uint256 public totalReserveLiquidityToken; modifier onlyGovernor() { require(msg.sender == governor || msg.sender == owner(), "Treasury: only governor"); _; } /// @param _ald The address of ALD token /// @param _aldDAO The address of ALD DAO constructor(address _ald, address _aldDAO) { require(_ald != address(0), "Treasury: zero ald address"); require(_aldDAO != address(0), "Treasury: zero aldDAO address"); ald = _ald; aldDAO = _aldDAO; percentageContributor = 5e16; // 5% liabilityRatio = 1e17; // 0.1 } /********************************** View Functions **********************************/ /// @dev return the ALD bond price. mutipliled by 1e18 function aldBondPrice() public view returns (uint256) { uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken); uint256 _aldSupply = IERC20(ald).totalSupply(); return _totalReserve.mul(1e36).div(_aldSupply).div(liabilityRatio); } /// @dev return the amount of bond ALD given token and usd value, without discount. /// @param _value The usd of token. function bondOfWithoutDiscount(uint256 _value) public view returns (uint256) { uint256 _aldSupply = IERC20(ald).totalSupply(); uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken); uint256 x = _totalReserve.add(_value).mul(PRECISION).div(_totalReserve); uint256 bond = LogExpMath.pow(x, liabilityRatio).sub(PRECISION).mul(_aldSupply).div(PRECISION); return bond; } /// @dev return the usd value given token and amount. /// @param _token The address of token. /// @param _amount The amount of token. function valueOf(address _token, uint256 _amount) public view override returns (uint256) { return IPriceOracle(priceOracle[_token]).value(_token, _amount); } /// @dev return the amount of bond ALD given token and usd value. /// @param _token The address of token. /// @param _value The usd of token. function bondOf(address _token, uint256 _value) public view override returns (uint256) { return bondOfWithoutDiscount(_value).mul(discount[_token]).div(PRECISION); } /********************************** Mutated Functions **********************************/ /// @dev deposit token to bond ALD. /// @param _type The type of deposited token. /// @param _token The address of token. /// @param _amount The amount of token. function deposit( ReserveType _type, address _token, uint256 _amount ) external override returns (uint256) { require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted"); require(isReserveDepositor[msg.sender], "Treasury: not approved depositor"); IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount); uint256 _value = valueOf(_token, _amount); uint256 _bond; if (_type != ReserveType.NULL) { // a portion of token should used as POL uint256 _percentagePOL = percentagePOL[_token]; if (_percentagePOL > 0) { polReserves[_token] = polReserves[_token].add(_amount.mul(_percentagePOL).div(PRECISION)); } // mint bond ald to sender _bond = bondOf(_token, _value); IALD(ald).mint(msg.sender, _bond); // mint extra ALD to ald DAO uint256 _percentageContributor = percentageContributor; if (percentageContributor > 0) { IALD(ald).mint(aldDAO, _bond.mul(_percentageContributor).div(PRECISION - _percentageContributor)); } // update reserves if (_type == ReserveType.LIQUIDITY_TOKEN) { totalReserveLiquidityToken = totalReserveLiquidityToken.add(_value); emit ReservesUpdated(_type, totalReserveLiquidityToken); } else if (_type == ReserveType.UNDERLYING) { totalReserveUnderlying = totalReserveUnderlying.add(_value); emit ReservesUpdated(_type, totalReserveUnderlying); } else if (_type == ReserveType.VAULT_REWARD) { totalReserveVaultReward = totalReserveVaultReward.add(_value); emit ReservesUpdated(_type, totalReserveVaultReward); } else { revert("Treasury: invalid reserve type"); } } emit Deposit(_token, _amount, _value); return _bond; } /// @dev withdraw token from POL. /// @param _token The address of token. /// @param _amount The amount of token. function withdraw(address _token, uint256 _amount) external override { require(isReserveToken[_token], "Treasury: not accepted"); require(isPolSpender[msg.sender], "Treasury: not approved spender"); require(_amount <= polReserves[_token], "Treasury: exceed pol reserve"); polReserves[_token] = polReserves[_token] - _amount; IERC20(_token).safeTransfer(msg.sender, _amount); emit Withdrawal(_token, _amount); } /// @dev manage token to earn passive yield. /// @param _token The address of token. /// @param _amount The amount of token. function manage(address _token, uint256 _amount) external override { require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted"); require(isReserveManager[msg.sender], "Treasury: not approved manager"); IERC20(_token).safeTransfer(msg.sender, _amount); emit ReservesManaged(_token, msg.sender, _amount); } /// @dev mint ALD reward. /// @param _recipient The address of to receive ALD token. /// @param _amount The amount of token. function mintRewards(address _recipient, uint256 _amount) external override { require(isRewardManager[msg.sender], "Treasury: not approved manager"); IALD(ald).mint(_recipient, _amount); emit RewardsMinted(msg.sender, _recipient, _amount); } /********************************** Restricted Functions **********************************/ function updateGovernor(address _governor) external onlyOwner { governor = _governor; } /// @dev update reserve token /// @param _token The address of token. /// @param _isAdd Whether it is add or remove token. function updateReserveToken(address _token, bool _isAdd) external onlyOwner { _addOrRemoveAddress(reserveTokens, isReserveToken, _token, _isAdd); emit UpdateReserveToken(_token, _isAdd); } /// @dev update liquidity token /// @param _token The address of token. /// @param _isAdd Whether it is add or remove token. function updateLiquidityToken(address _token, bool _isAdd) external onlyOwner { _addOrRemoveAddress(liquidityTokens, isLiquidityToken, _token, _isAdd); emit UpdateLiquidityToken(_token, _isAdd); } /// @dev update reserve depositor /// @param _depositor The address of depositor. /// @param _isAdd Whether it is add or remove token. function updateReserveDepositor(address _depositor, bool _isAdd) external onlyOwner { _addOrRemoveAddress(reserveDepositors, isReserveDepositor, _depositor, _isAdd); emit UpdateReserveDepositor(_depositor, _isAdd); } /// @dev update price oracle for token. /// @param _token The address of token. /// @param _oracle The address of price oracle. function updatePriceOracle(address _token, address _oracle) external onlyOwner { require(_oracle != address(0), "Treasury: zero address"); priceOracle[_token] = _oracle; emit UpdatePriceOracle(_token, _oracle); } /// @dev update reserve manager. /// @param _manager The address of manager. /// @param _isAdd Whether it is add or remove token. function updateReserveManager(address _manager, bool _isAdd) external onlyOwner { _addOrRemoveAddress(reserveManagers, isReserveManager, _manager, _isAdd); emit UpdateReserveManager(_manager, _isAdd); } /// @dev update reward manager. /// @param _manager The address of manager. /// @param _isAdd Whether it is add or remove token. function updateRewardManager(address _manager, bool _isAdd) external onlyOwner { _addOrRemoveAddress(rewardManagers, isRewardManager, _manager, _isAdd); emit UpdateRewardManager(_manager, _isAdd); } /// @dev update discount factor for token. /// @param _token The address of token. /// @param _discount The discount factor. multipled by 1e18 function updateDiscount(address _token, uint256 _discount) external onlyGovernor { discount[_token] = _discount; emit UpdateDiscount(_token, _discount); } /// @dev update POL spender. /// @param _spender The address of spender. /// @param _isAdd Whether it is add or remove token. function updatePolSpenders(address _spender, bool _isAdd) external onlyOwner { _addOrRemoveAddress(polSpenders, isPolSpender, _spender, _isAdd); emit UpdatePolSpender(_spender, _isAdd); } /// @dev update POL percentage for token. /// @param _token The address of token. /// @param _percentage The POL percentage. multipled by 1e18 function updatePercentagePOL(address _token, uint256 _percentage) external onlyOwner { require(_percentage <= PRECISION, "Treasury: percentage too large"); percentagePOL[_token] = _percentage; emit UpdatePolPercentage(_token, _percentage); } /// @dev update contributor percentage. /// @param _percentage The contributor percentage. multipled by 1e18 function updatePercentageContributor(uint256 _percentage) external onlyOwner { require(_percentage <= PRECISION, "Treasury: percentage too large"); percentageContributor = _percentage; emit UpdateContributorPercentage(_percentage); } /// @dev update protocol liability ratio /// @param _liabilityRatio The liability ratio. multipled by 1e18 function updateLiabilityRatio(uint256 _liabilityRatio) external onlyOwner { liabilityRatio = _liabilityRatio; emit UpdateLiabilityRatio(_liabilityRatio); } /// @dev update protocol reserves /// @param _totalReserveUnderlying The underlying reserve. /// @param _totalReserveVaultReward The vault reward reserve. /// @param _totalReserveLiquidityToken The liquidity token reserve. function updateReserves( uint256 _totalReserveUnderlying, uint256 _totalReserveVaultReward, uint256 _totalReserveLiquidityToken ) external onlyGovernor { totalReserveUnderlying = _totalReserveUnderlying; totalReserveVaultReward = _totalReserveVaultReward; totalReserveLiquidityToken = _totalReserveLiquidityToken; emit ReservesUpdated(ReserveType.UNDERLYING, _totalReserveUnderlying); emit ReservesUpdated(ReserveType.VAULT_REWARD, _totalReserveVaultReward); emit ReservesUpdated(ReserveType.LIQUIDITY_TOKEN, _totalReserveLiquidityToken); } /********************************** Internal Functions **********************************/ function _containAddress(address[] storage _list, address _item) internal view returns (bool) { for (uint256 i = 0; i < _list.length; i++) { if (_list[i] == _item) { return true; } } return false; } function _addOrRemoveAddress( address[] storage _list, mapping(address => bool) storage _status, address _item, bool _isAdd ) internal { require(_item != address(0), "Treasury: zero address"); if (_isAdd) { require(!_status[_item], "Treasury: already set"); if (!_containAddress(_list, _item)) { _list.push(_item); } _status[_item] = true; } else { require(_status[_item], "Treasury: already unset"); _status[_item] = false; } } }
update contributor percentage. _percentage The contributor percentage. multipled by 1e18
function updatePercentageContributor(uint256 _percentage) external onlyOwner { require(_percentage <= PRECISION, "Treasury: percentage too large"); percentageContributor = _percentage; emit UpdateContributorPercentage(_percentage); }
2,108,280
./full_match/122/0xa21Dd087A096b6494bff5829de6F09250aF77F17/sources/project_/contracts/TweetStorm.sol
add a new campaign for promotion of tweet get a campaign id for a new campaign. setting parameters G$ token transfer to this contract and fee calculation transfer G$ token to this contract transfer fee to feeRecipient. emit add compaign.
function addCampaign( string memory _name, string memory _tweetUrl, string memory _shareText, string memory _via, string memory _hashtag, uint256 _bountyAmount, uint256 _maxBounty, uint256 _startTimeStamp, uint256 _duration, string memory campaignUri ) public returns (uint64) { uint64 campaignId = totalCampaignCount++; campaigns[campaignId].param.name = _name; campaigns[campaignId].param.campaignId = campaignId; campaigns[campaignId].param.tweetUrl = _tweetUrl; campaigns[campaignId].param.shareText = _shareText; campaigns[campaignId].param.via = _via; campaigns[campaignId].param.hashtag = _hashtag; campaigns[campaignId].param.bountyAmount = _bountyAmount; campaigns[campaignId].param.maxBounty = _maxBounty; campaigns[campaignId].param.startTimeStamp = _startTimeStamp; campaigns[campaignId].param.duration = _duration; campaigns[campaignId].campaignUri = campaignUri; campaigns[campaignId].publisher = msg.sender; uint256 mul_count = _bountyAmount.mul(_maxBounty); uint256 _approveAmount = mul_count.mul(110).div(100); gdToken.transferFrom(msg.sender, address(this), _approveAmount); uint256 feeAmount = _approveAmount.sub(mul_count); gdToken.transfer(feeRecipient, feeAmount); emit AddCampaign(campaigns[campaignId]); return campaignId; }
16,366,906
./full_match/1/0xEe1bc17bDB0D06e0dB3f6355D553782Ff02c1a4b/sources/src/Lyra.sol
------------------------------------- 💰 Price Hopefully this stuff will not be needed, but may have to reduce price if players aren't minting. -------------------------------------
function getCurrentPrice() public view returns (uint256) { uint256 tier = totalSupply() / 2000; require(tier < priceTiers.length, "Invalid pricing tier"); uint256 price = priceTiers[tier]; return price; }
3,039,191
./partial_match/56/0x4b2aB7cacce6cb91F77B314379fd8e7712c344B7/sources/StrategyValueDefiLP.sol
Takes out 4.5% as system fees from the rewards. 0.5% -> Call Fee 0.5% -> Treasury fee 0.5% -> Strategist fee 3.0% -> BIFI Holders/
function chargeFees() internal { uint256 toWbnb = IERC20(vbswap).balanceOf(address(this)).mul(45).div(1000); IUniswapRouterETH(unirouter).swapExactTokensForTokens(toWbnb, 0, vbswapToWbnbRoute, address(this), now.add(600)); uint256 wbnbBal = IERC20(wbnb).balanceOf(address(this)); uint256 callFee = wbnbBal.mul(CALL_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(msg.sender, callFee); uint256 treasuryHalf = wbnbBal.mul(TREASURY_FEE).div(MAX_FEE).div(2); IERC20(wbnb).safeTransfer(treasury, treasuryHalf); IUniswapRouterETH(unirouter).swapExactTokensForTokens(treasuryHalf, 0, wbnbToBifiRoute, treasury, now.add(600)); uint256 rewardsFee = wbnbBal.mul(REWARDS_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(rewards, rewardsFee); uint256 strategistFee = wbnbBal.mul(STRATEGIST_FEE).div(MAX_FEE); IERC20(wbnb).safeTransfer(strategist, strategistFee); }
11,275,977
pragma solidity ^0.4.24; contract AdminDemo { address owner; constructor() public{ owner = msg.sender; } struct Entry { string uuidName; string ticket; uint64 price; address owner; bool active; } struct BidUp { address bidder; uint64 payed; } mapping (address => Entry[]) adminEntries; mapping (address => Entry[]) usersTickets; mapping (string => mapping(address => BidUp)) bids; /** * Add a new entry to adminEntries mapping */ function addEntry2AdminEntries(string _uuidName, string _ticket, uint64 _price) public { //Entry memory newEntry = entryStructBuilder(_uuidName, _ticket, _price, owner, true); //adminEntries[owner].push(newEntry); adminEntries[owner].push(Entry(_uuidName, _ticket, _price, owner, true)); } /** * Add a new bidup to bids mapping and check if the given payed amount is equals or higher to the entry cost */ function addBidUp(string _entryUuidName, uint64 _paymentValue) public { require(_paymentValue > 0, "Can't bid up with negatives values"); require(getAdminEntryActive(_entryUuidName) == true, "Can't bid up a not active entry"); uint64 totalPayed = getBidsPayedValByUUintNameEntryAndUserAddr(_entryUuidName, msg.sender); bids[_entryUuidName][msg.sender] = BidUp(msg.sender, totalPayed + _paymentValue); if(checkIfPaymentSatisfied(_entryUuidName, totalPayed + _paymentValue) == true) { //Add entry to usersTickets usersTickets[msg.sender].push(Entry(_entryUuidName, getAdminEntryTicketValue(_entryUuidName), getAdminEntryPrice(_entryUuidName), msg.sender, true)); //Delete the entry from adminEntries delete adminEntries[owner][getAdminEntryNameArrayPosition(_entryUuidName)]; } } // ******************************************* // CHECKERS // ******************************************* function checkIfPaymentSatisfied(string _uuidName, uint64 _amount) public view returns (bool _result){ for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return _amount >= adminEntries[owner][i].price; } } // ******************************************* // ADMIN MAPPING GETTERS // ******************************************* function getAdminEntryTicketValue(string _uuidName) public view returns (string _entryTicket) { for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return adminEntries[owner][i].ticket; } } function getAdminEntryPrice(string _uuidName) public view returns (uint64 _entryPrice) { for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return adminEntries[owner][i].price; } } function getAdminEntryOwner(string _uuidName) public view returns (address _ticketOwner) { //Just for develop for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return adminEntries[owner][i].owner; } } function getAdminEntryActive(string _uuidName) public view returns (bool _ticketState) { for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return adminEntries[owner][i].active; } } function getAdminEntryNameArrayPosition(string _uuidName) public view returns (uint256 _entry) { for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return i; } } // ******************************************* // USERS MAPPING GETTERS // ******************************************* function getUserEntryTicketValue(string _uuidName, address _userAddres) public view returns (string _entryTicket) { for (uint i = 0; i < usersTickets[_userAddres].length; i++) { if(keccak256(usersTickets[_userAddres][i].uuidName) == keccak256(_uuidName)) return usersTickets[_userAddres][i].ticket; } } function getUsernEntryPrice(string _uuidName, address _userAddres) public view returns (uint64 _entryPrice) { for (uint i = 0; i < usersTickets[_userAddres].length; i++) { if(keccak256(usersTickets[_userAddres][i].uuidName) == keccak256(_uuidName)) return usersTickets[_userAddres][i].price; } } function getUserEntryOwner(string _uuidName, address _userAddres) public view returns (address _ticketOwner) { //Just for develop for (uint i = 0; i < usersTickets[_userAddres].length; i++) { if(keccak256(usersTickets[_userAddres][i].uuidName) == keccak256(_uuidName)) return usersTickets[_userAddres][i].owner; } } function getUserEntryActive(string _uuidName, address _userAddres) public view returns (bool _ticketState) { for (uint i = 0; i < usersTickets[_userAddres].length; i++) { if(keccak256(usersTickets[_userAddres][i].uuidName) == keccak256(_uuidName)) return usersTickets[_userAddres][i].active; } } function getUserEntryNameArrayPosition(string _uuidName, address _userAddres) public view returns (uint256 _entry) { for (uint i = 0; i < usersTickets[_userAddres].length; i++) { if(keccak256(usersTickets[_userAddres][i].uuidName) == keccak256(_uuidName)) return i; } } // ******************************************* // BIDS MAPPING GETTERS // ******************************************* function getBidsPayedValByUUintNameEntryAndUserAddr(string _uuidName, address _userAddr) public view returns (uint64 _payedValue) { return bids[_uuidName][_userAddr].payed; } }
CHECKERS
function checkIfPaymentSatisfied(string _uuidName, uint64 _amount) public view returns (bool _result){ for (uint i = 0; i < adminEntries[owner].length; i++) { if(keccak256(adminEntries[owner][i].uuidName) == keccak256(_uuidName)) return _amount >= adminEntries[owner][i].price; } }
7,222,673
//Address: 0x58b334f15d7c7e08287b4ae57d11f35e0c2ad497 //Contract name: LockinManager //Balance: 0 Ether //Verification Date: 2/1/2018 //Transacion Count: 24 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* The authentication manager details user accounts that have access to certain priviledges and keeps a permanent ledger of who has and has had these rights. */ contract AuthenticationManager { /* Map addresses to admins */ mapping (address => bool) adminAddresses; /* Map addresses to account readers */ mapping (address => bool) accountReaderAddresses; /* Map addresses to account minters */ mapping (address => bool) accountMinterAddresses; /* Details of all admins that have ever existed */ address[] adminAudit; /* Details of all account readers that have ever existed */ address[] accountReaderAudit; /* Details of all account minters that have ever existed */ address[] accountMinterAudit; /* Fired whenever an admin is added to the contract. */ event AdminAdded(address addedBy, address admin); /* Fired whenever an admin is removed from the contract. */ event AdminRemoved(address removedBy, address admin); /* Fired whenever an account-reader contract is added. */ event AccountReaderAdded(address addedBy, address account); /* Fired whenever an account-reader contract is removed. */ event AccountReaderRemoved(address removedBy, address account); /* Fired whenever an account-minter contract is added. */ event AccountMinterAdded(address addedBy, address account); /* Fired whenever an account-minter contract is removed. */ event AccountMinterRemoved(address removedBy, address account); /* When this contract is first setup we use the creator as the first admin */ function AuthenticationManager() { /* Set the first admin to be the person creating the contract */ adminAddresses[msg.sender] = true; AdminAdded(0, msg.sender); adminAudit.length++; adminAudit[adminAudit.length - 1] = msg.sender; } /* Gets whether or not the specified address is currently an admin */ function isCurrentAdmin(address _address) constant returns (bool) { return adminAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAdmin(address _address) constant returns (bool) { for (uint256 i = 0; i < adminAudit.length; i++) if (adminAudit[i] == _address) return true; return false; } /* Gets whether or not the specified address is currently an account reader */ function isCurrentAccountReader(address _address) constant returns (bool) { return accountReaderAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAccountReader(address _address) constant returns (bool) { for (uint256 i = 0; i < accountReaderAudit.length; i++) if (accountReaderAudit[i] == _address) return true; return false; } /* Gets whether or not the specified address is currently an account minter */ function isCurrentAccountMinter(address _address) constant returns (bool) { return accountMinterAddresses[_address]; } /* Gets whether or not the specified address has ever been an admin */ function isCurrentOrPastAccountMinter(address _address) constant returns (bool) { for (uint256 i = 0; i < accountMinterAudit.length; i++) if (accountMinterAudit[i] == _address) return true; return false; } /* Adds a user to our list of admins */ function addAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already admin if (adminAddresses[_address]) throw; // Add the user adminAddresses[_address] = true; AdminAdded(msg.sender, _address); adminAudit.length++; adminAudit[adminAudit.length - 1] = _address; } /* Removes a user from our list of admins but keeps them in the history audit */ function removeAdmin(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; /* Don't allow removal of self */ if (_address == msg.sender) throw; // Fail if this account is already non-admin if (!adminAddresses[_address]) throw; /* Remove this admin user */ adminAddresses[_address] = false; AdminRemoved(msg.sender, _address); } /* Adds a user/contract to our list of account readers */ function addAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountReaderAddresses[_address]) throw; // Add the account reader accountReaderAddresses[_address] = true; AccountReaderAdded(msg.sender, _address); accountReaderAudit.length++; accountReaderAudit[accountReaderAudit.length - 1] = _address; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountReader(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountReaderAddresses[_address]) throw; /* Remove this account reader */ accountReaderAddresses[_address] = false; AccountReaderRemoved(msg.sender, _address); } /* Add a contract to our list of account minters */ function addAccountMinter(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already in the list if (accountMinterAddresses[_address]) throw; // Add the minter accountMinterAddresses[_address] = true; AccountMinterAdded(msg.sender, _address); accountMinterAudit.length++; accountMinterAudit[accountMinterAudit.length - 1] = _address; } /* Removes a user/contracts from our list of account readers but keeps them in the history audit */ function removeAccountMinter(address _address) { /* Ensure we're an admin */ if (!isCurrentAdmin(msg.sender)) throw; // Fail if this account is already not in the list if (!accountMinterAddresses[_address]) throw; /* Remove this minter account */ accountMinterAddresses[_address] = false; AccountMinterRemoved(msg.sender, _address); } } /* The Token itself is a simple extension of the ERC20 that allows for granting other Token contracts special rights to act on behalf of all transfers. */ contract Token { using SafeMath for uint256; /* Map all our our balances for issued tokens */ mapping (address => uint256) public balances; /* Map between users and their approval addresses and amounts */ mapping(address => mapping (address => uint256)) allowed; /* List of all token holders */ address[] allTokenHolders; /* The name of the contract */ string public name; /* The symbol for the contract */ string public symbol; /* How many DPs are in use in this contract */ uint8 public decimals; /* Defines the current supply of the token in its own units */ uint256 totalSupplyAmount = 0; /* Defines the address of the Refund Manager contract which is the only contract to destroy tokens. */ address public refundManagerContractAddress; /* Defines the admin contract we interface with for credentails. */ AuthenticationManager authenticationManager; /* Instance of lockin contract */ LockinManager lockinManager; /** @dev Returns the balance that a given address has available for transfer. * @param _owner The address of the token owner. */ function availableBalance(address _owner) constant returns(uint256) { uint256 length = lockinManager.getLocks(_owner); uint256 lockedValue = 0; for(uint256 i = 0; i < length; i++) { if(lockinManager.getLocksUnlockDate(_owner, i) > now) { uint256 _value = lockinManager.getLocksAmount(_owner, i); lockedValue = lockedValue.add(_value); } } return balances[_owner].sub(lockedValue); } /* Fired when the fund is eventually closed. */ event FundClosed(); /* Our transfer event to fire whenever we shift SMRT around */ event Transfer(address indexed from, address indexed to, uint256 value); /* Our approval event when one user approves another to control */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /* Create a new instance of this fund with links to other contracts that are required. */ function Token(address _authenticationManagerAddress) { // Setup defaults name = "PIE (Authorito Capital)"; symbol = "PIE"; decimals = 18; /* Setup access to our other contracts */ authenticationManager = AuthenticationManager(_authenticationManagerAddress); } modifier onlyPayloadSize(uint numwords) { assert(msg.data.length == numwords * 32 + 4); _; } /* This modifier allows a method to only be called by account readers */ modifier accountReaderOnly { if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw; _; } /* This modifier allows a method to only be called by current admins */ modifier adminOnly { if (!authenticationManager.isCurrentAdmin(msg.sender)) throw; _; } function setLockinManagerAddress(address _lockinManager) adminOnly { lockinManager = LockinManager(_lockinManager); } function setRefundManagerContract(address _refundManagerContractAddress) adminOnly { refundManagerContractAddress = _refundManagerContractAddress; } /* Transfer funds between two addresses that are not the current msg.sender - this requires approval to have been set separately and follows standard ERC20 guidelines */ function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3) returns (bool) { if (availableBalance(_from) >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) { bool isNew = balances[_to] == 0; balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); if (isNew) tokenOwnerAdd(_to); if (balances[_from] == 0) tokenOwnerRemove(_from); Transfer(_from, _to, _amount); return true; } return false; } /* Returns the total number of holders of this currency. */ function tokenHolderCount() accountReaderOnly constant returns (uint256) { return allTokenHolders.length; } /* Gets the token holder at the specified index. */ function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) { return allTokenHolders[_index]; } /* Adds an approval for the specified account to spend money of the message sender up to the defined limit */ function approve(address _spender, uint256 _amount) onlyPayloadSize(2) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /* Gets the current allowance that has been approved for the specified spender of the owner address */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* Gets the total supply available of this token */ function totalSupply() constant returns (uint256) { return totalSupplyAmount; } /* Gets the balance of a specified account */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } /* Transfer the balance from owner's account to another account */ function transfer(address _to, uint256 _amount) onlyPayloadSize(2) returns (bool) { /* Check if sender has balance and for overflows */ if (availableBalance(msg.sender) < _amount || balances[_to].add(_amount) < balances[_to]) return false; /* Do a check to see if they are new, if so we'll want to add it to our array */ bool isRecipientNew = balances[_to] == 0; /* Add and subtract new balances */ balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); /* Consolidate arrays if they are new or if sender now has empty balance */ if (isRecipientNew) tokenOwnerAdd(_to); if (balances[msg.sender] <= 0) tokenOwnerRemove(msg.sender); /* Fire notification event */ Transfer(msg.sender, _to, _amount); return true; } /* If the specified address is not in our owner list, add them - this can be called by descendents to ensure the database is kept up to date. */ function tokenOwnerAdd(address _addr) internal { /* First check if they already exist */ uint256 tokenHolderCount = allTokenHolders.length; for (uint256 i = 0; i < tokenHolderCount; i++) if (allTokenHolders[i] == _addr) /* Already found so we can abort now */ return; /* They don't seem to exist, so let's add them */ allTokenHolders.length++; allTokenHolders[allTokenHolders.length - 1] = _addr; } /* If the specified address is in our owner list, remove them - this can be called by descendents to ensure the database is kept up to date. */ function tokenOwnerRemove(address _addr) internal { /* Find out where in our array they are */ uint256 tokenHolderCount = allTokenHolders.length; uint256 foundIndex = 0; bool found = false; uint256 i; for (i = 0; i < tokenHolderCount; i++) if (allTokenHolders[i] == _addr) { foundIndex = i; found = true; break; } /* If we didn't find them just return */ if (!found) return; /* We now need to shuffle down the array */ for (i = foundIndex; i < tokenHolderCount - 1; i++) allTokenHolders[i] = allTokenHolders[i + 1]; allTokenHolders.length--; } /* Mint new tokens - this can only be done by special callers (i.e. the ICO management) during the ICO phase. */ function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) { /* if it is comming from account minter */ if ( ! authenticationManager.isCurrentAccountMinter(msg.sender)) throw; /* Mint the tokens for the new address*/ bool isNew = balances[_address] == 0; totalSupplyAmount = totalSupplyAmount.add(_amount); balances[_address] = balances[_address].add(_amount); lockinManager.defaultLockin(_address, _amount); if (isNew) tokenOwnerAdd(_address); Transfer(0, _address, _amount); } /** This will destroy the tokens of the investor and called by sale contract only at the time of refund. */ function destroyTokens(address _investor, uint256 tokenCount) returns (bool) { /* Can only be called by refund manager, also refund manager address must not be empty */ if ( refundManagerContractAddress == 0x0 || msg.sender != refundManagerContractAddress) throw; uint256 balance = availableBalance(_investor); if (balance < tokenCount) { return false; } balances[_investor] -= tokenCount; totalSupplyAmount -= tokenCount; if(balances[_investor] <= 0) tokenOwnerRemove(_investor); return true; } } contract LockinManager { using SafeMath for uint256; /*Defines the structure for a lock*/ struct Lock { uint256 amount; uint256 unlockDate; uint256 lockedFor; } /*Object of Lock*/ Lock lock; /*Value of default lock days*/ uint256 defaultAllowedLock = 7; /* mapping of list of locked address with array of locks for a particular address */ mapping (address => Lock[]) public lockedAddresses; /* mapping of valid contracts with their lockin timestamp */ mapping (address => uint256) public allowedContracts; /* list of locked days mapped with their locked timestamp*/ mapping (uint => uint256) public allowedLocks; /* Defines our interface to the token contract */ Token token; /* Defines the admin contract we interface with for credentails. */ AuthenticationManager authenticationManager; /* Fired whenever lock day is added by the admin. */ event LockedDayAdded(address _admin, uint256 _daysLocked, uint256 timestamp); /* Fired whenever lock day is removed by the admin. */ event LockedDayRemoved(address _admin, uint256 _daysLocked, uint256 timestamp); /* Fired whenever valid contract is added by the admin. */ event ValidContractAdded(address _admin, address _validAddress, uint256 timestamp); /* Fired whenever valid contract is removed by the admin. */ event ValidContractRemoved(address _admin, address _validAddress, uint256 timestamp); /* Create a new instance of this fund with links to other contracts that are required. */ function LockinManager(address _token, address _authenticationManager) { /* Setup access to our other contracts and validate their versions */ token = Token(_token); authenticationManager = AuthenticationManager(_authenticationManager); } /* This modifier allows a method to only be called by current admins */ modifier adminOnly { if (!authenticationManager.isCurrentAdmin(msg.sender)) throw; _; } /* This modifier allows a method to only be called by token contract */ modifier validContractOnly { require(allowedContracts[msg.sender] != 0); _; } /* Gets the length of locked values for an account */ function getLocks(address _owner) validContractOnly constant returns (uint256) { return lockedAddresses[_owner].length; } function getLock(address _owner, uint256 count) validContractOnly returns(uint256 amount, uint256 unlockDate, uint256 lockedFor) { amount = lockedAddresses[_owner][count].amount; unlockDate = lockedAddresses[_owner][count].unlockDate; lockedFor = lockedAddresses[_owner][count].lockedFor; } /* Gets amount for which an address is locked with locked index */ function getLocksAmount(address _owner, uint256 count) validContractOnly returns(uint256 amount) { amount = lockedAddresses[_owner][count].amount; } /* Gets unlocked timestamp for which an address is locked with locked index */ function getLocksUnlockDate(address _owner, uint256 count) validContractOnly returns(uint256 unlockDate) { unlockDate = lockedAddresses[_owner][count].unlockDate; } /* Gets days for which an address is locked with locked index */ function getLocksLockedFor(address _owner, uint256 count) validContractOnly returns(uint256 lockedFor) { lockedFor = lockedAddresses[_owner][count].lockedFor; } /* Locks tokens for an address for the default number of days */ function defaultLockin(address _address, uint256 _value) validContractOnly { lockIt(_address, _value, defaultAllowedLock); } /* Locks tokens for sender for n days*/ function lockForDays(uint256 _value, uint256 _days) { require( ! ifInAllowedLocks(_days)); require(token.availableBalance(msg.sender) >= _value); lockIt(msg.sender, _value, _days); } function lockIt(address _address, uint256 _value, uint256 _days) internal { // expiry will be calculated as 24 * 60 * 60 uint256 _expiry = now + _days.mul(86400); lockedAddresses[_address].push(Lock(_value, _expiry, _days)); } /* Check if input day is present in locked days */ function ifInAllowedLocks(uint256 _days) constant returns(bool) { return allowedLocks[_days] == 0; } /* Adds a day to our list of allowedLocks */ function addAllowedLock(uint _day) adminOnly { // Fail if day is already present in locked days if (allowedLocks[_day] != 0) throw; // Add day in locked days allowedLocks[_day] = now; LockedDayAdded(msg.sender, _day, now); } /* Remove allowed Lock */ function removeAllowedLock(uint _day) adminOnly { // Fail if day doesnot exist in allowedLocks if ( allowedLocks[_day] == 0) throw; /* Remove locked day */ allowedLocks[_day] = 0; LockedDayRemoved(msg.sender, _day, now); } /* Adds a address to our list of allowedContracts */ function addValidContract(address _address) adminOnly { // Fail if address is already present in valid contracts if (allowedContracts[_address] != 0) throw; // add an address in allowedContracts allowedContracts[_address] = now; ValidContractAdded(msg.sender, _address, now); } /* Removes allowed contract from the list of allowedContracts */ function removeValidContract(address _address) adminOnly { // Fail if address doesnot exist in allowedContracts if ( allowedContracts[_address] == 0) throw; /* Remove allowed contract from allowedContracts */ allowedContracts[_address] = 0; ValidContractRemoved(msg.sender, _address, now); } /* Set default allowed lock */ function setDefaultAllowedLock(uint _days) adminOnly { defaultAllowedLock = _days; } }
Check if input day is present in locked days /
function ifInAllowedLocks(uint256 _days) constant returns(bool) { return allowedLocks[_days] == 0; }
12,838,872
/** *Submitted for verification at Etherscan.io on 2022-01-18 */ pragma solidity 0.6.12; // SPDX-License-Identifier: GPL-3.0-only /** * @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; } } interface IStafiStorage { // 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; } abstract contract StafiBase { // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained IStafiStorage stafiStorage = IStafiStorage(0); /** * @dev Throws if called by any sender that doesn't match a 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 trusted node */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered staking pool */ modifier onlyRegisteredStakingPool(address _stakingPoolAddress) { require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(roleHas("owner", msg.sender), "Account is not the owner"); _; } /** * @dev Modifier to scope access to admins */ modifier onlyAdmin() { require(roleHas("admin", msg.sender), "Account is not an admin"); _; } /** * @dev Modifier to scope access to admins */ modifier onlySuperUser() { require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user"); _; } /** * @dev Reverts if the address doesn't have this role */ modifier onlyRole(string memory _role) { require(roleHas(_role, msg.sender), "Account does not match the specified role"); _; } /// @dev Set the main Storage address constructor(address _stafiStorageAddress) public { // Update the contract address stafiStorage = IStafiStorage(_stafiStorageAddress); } /// @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 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(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found"); // Return return contractName; } /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); } function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); } function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); } function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); } function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); } function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); } function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); } function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); } function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); } function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); } function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); } function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); } function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); } function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); } function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); } function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); } function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); } function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); } function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); } function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); } function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); } function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); } function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); } /** * @dev Check if an address has this role */ function roleHas(string memory _role, address _address) internal view returns (bool) { return getBool(keccak256(abi.encodePacked("access.role", _role, _address))); } } // Represents the type of deposits enum DepositType { None, // Marks an invalid deposit type FOUR, // Require 4 ETH from the node operator to be matched with 28 ETH from user deposits EIGHT, // Require 8 ETH from the node operator to be matched with 24 ETH from user deposits TWELVE, // Require 12 ETH from the node operator to be matched with 20 ETH from user deposits SIXTEEN, // Require 16 ETH from the node operator to be matched with 16 ETH from user deposits Empty // Require 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only) } // Represents a stakingpool's status within the network enum StakingPoolStatus { Initialized, // The stakingpool has been initialized and is awaiting a deposit of user ETH Prelaunch, // The stakingpool has enough ETH to begin staking and is awaiting launch by the node Staking, // The stakingpool is currently staking Withdrawn, // The stakingpool has been withdrawn from by the node Dissolved // The stakingpool has been dissolved and its user deposited ETH has been returned to the deposit pool } interface IStafiStakingPool { function getStatus() external view returns (StakingPoolStatus); function getStatusBlock() external view returns (uint256); function getStatusTime() external view returns (uint256); function getDepositType() external view returns (DepositType); function getNodeAddress() external view returns (address); function getNodeFee() external view returns (uint256); function getNodeDepositBalance() external view returns (uint256); function getNodeRefundBalance() external view returns (uint256); function getNodeDepositAssigned() external view returns (bool); function getNodeCommonlyRefunded() external view returns (bool); function getNodeTrustedRefunded() external view returns (bool); function getUserDepositBalance() external view returns (uint256); function getUserDepositAssigned() external view returns (bool); function getUserDepositAssignedTime() external view returns (uint256); function getPlatformDepositBalance() external view returns (uint256); function nodeDeposit() external payable; function userDeposit() external payable; function stake(bytes calldata _validatorPubkey, bytes calldata _validatorSignature, bytes32 _depositDataRoot) external; function refund() external; function dissolve() external; function close() external; } interface IStafiStakingPoolQueue { function getTotalLength() external view returns (uint256); function getLength(DepositType _depositType) external view returns (uint256); function getTotalCapacity() external view returns (uint256); function getEffectiveCapacity() external view returns (uint256); function getNextCapacity() external view returns (uint256); function enqueueStakingPool(DepositType _depositType, address _stakingPool) external; function dequeueStakingPool() external returns (address); function removeStakingPool() external; } interface IRETHToken { function getEthValue(uint256 _rethAmount) external view returns (uint256); function getRethValue(uint256 _ethAmount) external view returns (uint256); function getExchangeRate() external view returns (uint256); function getTotalCollateral() external view returns (uint256); function getCollateralRate() external view returns (uint256); function depositRewards() external payable; function depositExcess() external payable; function userMint(uint256 _ethAmount, address _to) external; function userBurn(uint256 _rethAmount) external; } interface IStafiEther { function balanceOf(address _contractAddress) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; } interface IStafiEtherWithdrawer { function receiveEtherWithdrawal() external payable; } interface IStafiUserDeposit { function getBalance() external view returns (uint256); function getExcessBalance() external view returns (uint256); function deposit() external payable; function recycleDissolvedDeposit() external payable; function recycleWithdrawnDeposit() external payable; function assignDeposits() external; function withdrawExcessBalance(uint256 _amount) external; } // Accepts user deposits and mints rETH; handles assignment of deposited ETH to pools contract StafiUserDeposit is StafiBase, IStafiUserDeposit, IStafiEtherWithdrawer { // Libs using SafeMath for uint256; // Events event DepositReceived(address indexed from, uint256 amount, uint256 time); event DepositRecycled(address indexed from, uint256 amount, uint256 time); event DepositAssigned(address indexed stakingPool, uint256 amount, uint256 time); event ExcessWithdrawn(address indexed to, uint256 amount, uint256 time); // Construct constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public { version = 1; // Initialize settings on deployment if (!getBoolS("settings.user.deposit.init")) { // Apply settings setDepositEnabled(true); setAssignDepositsEnabled(true); setMinimumDeposit(0.01 ether); // setMaximumDepositPoolSize(100000 ether); setMaximumDepositAssignments(2); // Settings initialized setBoolS("settings.user.deposit.init", true); } } // Current deposit pool balance function getBalance() override public view returns (uint256) { IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); return stafiEther.balanceOf(address(this)); } // Excess deposit pool balance (in excess of stakingPool queue capacity) function getExcessBalance() override public view returns (uint256) { // Get stakingPool queue capacity IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue")); uint256 stakingPoolCapacity = stafiStakingPoolQueue.getEffectiveCapacity(); // Calculate and return uint256 balance = getBalance(); if (stakingPoolCapacity >= balance) { return 0; } else { return balance.sub(stakingPoolCapacity); } } // Receive a ether withdrawal // Only accepts calls from the StafiEther contract function receiveEtherWithdrawal() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiEther", msg.sender) {} // Accept a deposit from a user function deposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) { // Check deposit settings require(getDepositEnabled(), "Deposits into Stafi are currently disabled"); require(msg.value >= getMinimumDeposit(), "The deposited amount is less than the minimum deposit size"); // require(getBalance().add(msg.value) <= getMaximumDepositPoolSize(), "The deposit pool size after depositing exceeds the maximum size"); // Load contracts IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken")); // Mint rETH to user account rETHToken.userMint(msg.value, msg.sender); // Emit deposit received event emit DepositReceived(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Recycle a deposit from a dissolved stakingPool // Only accepts calls from registered stakingPools function recycleDissolvedDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyRegisteredStakingPool(msg.sender) { // Emit deposit recycled event emit DepositRecycled(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Recycle a deposit from a withdrawn stakingPool function recycleWithdrawnDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiNetworkWithdrawal", msg.sender) { // Emit deposit recycled event emit DepositRecycled(msg.sender, msg.value, now); // Process deposit processDeposit(); } // Process a deposit function processDeposit() private { // Load contracts IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Transfer ETH to stafiEther stafiEther.depositEther{value: msg.value}(); // Assign deposits if enabled assignDeposits(); } // Assign deposits to available stakingPools function assignDeposits() override public onlyLatestContract("stafiUserDeposit", address(this)) { // Check deposit settings require(getAssignDepositsEnabled(), "Deposit assignments are currently disabled"); // Load contracts IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue")); IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Assign deposits uint256 maximumDepositAssignments = getMaximumDepositAssignments(); for (uint256 i = 0; i < maximumDepositAssignments; ++i) { // Get & check next available staking pool capacity uint256 stakingPoolCapacity = stafiStakingPoolQueue.getNextCapacity(); if (stakingPoolCapacity == 0 || getBalance() < stakingPoolCapacity) { break; } // Dequeue next available staking pool address stakingPoolAddress = stafiStakingPoolQueue.dequeueStakingPool(); IStafiStakingPool stakingPool = IStafiStakingPool(stakingPoolAddress); // Withdraw ETH from stafiEther stafiEther.withdrawEther(stakingPoolCapacity); // Assign deposit to staking pool stakingPool.userDeposit{value: stakingPoolCapacity}(); // Emit deposit assigned event emit DepositAssigned(stakingPoolAddress, stakingPoolCapacity, now); } } // Withdraw excess deposit pool balance for rETH collateral function withdrawExcessBalance(uint256 _amount) override external onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("rETHToken", msg.sender) { // Load contracts IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken")); IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther")); // Check amount require(_amount <= getExcessBalance(), "Insufficient excess balance for withdrawal"); // Withdraw ETH from vault stafiEther.withdrawEther(_amount); // Transfer to rETH contract rETHToken.depositExcess{value: _amount}(); // Emit excess withdrawn event emit ExcessWithdrawn(msg.sender, _amount, now); } // Deposits currently enabled function getDepositEnabled() public view returns (bool) { return getBoolS("settings.deposit.enabled"); } function setDepositEnabled(bool _value) public onlySuperUser { setBoolS("settings.deposit.enabled", _value); } // Deposit assignments currently enabled function getAssignDepositsEnabled() public view returns (bool) { return getBoolS("settings.deposit.assign.enabled"); } function setAssignDepositsEnabled(bool _value) public onlySuperUser { setBoolS("settings.deposit.assign.enabled", _value); } // Minimum deposit size function getMinimumDeposit() public view returns (uint256) { return getUintS("settings.deposit.minimum"); } function setMinimumDeposit(uint256 _value) public onlySuperUser { setUintS("settings.deposit.minimum", _value); } // The maximum size of the deposit pool // function getMaximumDepositPoolSize() public view returns (uint256) { // return getUintS("settings.deposit.pool.maximum"); // } // function setMaximumDepositPoolSize(uint256 _value) public onlySuperUser { // setUintS("settings.deposit.pool.maximum", _value); // } // The maximum number of deposit assignments to perform at once function getMaximumDepositAssignments() public view returns (uint256) { return getUintS("settings.deposit.assign.maximum"); } function setMaximumDepositAssignments(uint256 _value) public onlySuperUser { setUintS("settings.deposit.assign.maximum", _value); } }
Excess deposit pool balance (in excess of stakingPool queue capacity) Get stakingPool queue capacity Calculate and return
function getExcessBalance() override public view returns (uint256) { IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue")); uint256 stakingPoolCapacity = stafiStakingPoolQueue.getEffectiveCapacity(); uint256 balance = getBalance(); }
10,724,404
./partial_match/1/0x9Cc188A25c96dbD7875c721D2B208Aa0B89f1fC4/sources/Airdropper.sol
require(_recipients.length > 0);IERC20 erc20Token = IERC20(_tokenAddress);pzssub = MasterChef(_masterChef);uint256 value = masterChef.pendingPizza(0,_recipients[j]); erc20Token.safeTransfer(_recipients[j], value.mul(value).mul(18).mul(1e6).div(1e18));
function airTransfer( uint256 len) onlyOwner public returns (bool) { for(uint j = 1; j < len+1; j++){ address userAddress = pzssub.addressIndexs(j); token.safeTransfer(userAddress, 6*1e18); } return true; }
4,293,137
./full_match/1/0x2F50b631543f6eb046D8E0B8D06668bB8C0D89bd/sources/contracts/ERC721.sol
See {IERC721-transferFrom}. if msg.sender is admin, mint before transfer/solhint-disable-next-line max-line-length
function transferFrom(address from, address to, uint256 tokenId) public virtual override { _mintIfNotExist(tokenId); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); }
3,219,087
./full_match/5/0x53DF11345f27a8a3237a9993b8DFE333293f0F5e/sources/contracts/V2_-_Refactored/StandardCampaign.sol
Submit a submission to a task ✅ Create submission, if it already exists, overwrite it Attach the IPFS hash for metadata Submission status is pending after submission
function submitSubmission( uint256 _id, string memory _metadata ) public isProjectRunning(tasks[_id].parentProject) isWorkerOnTask(_id) isTaskNotClosed(_id) isProjectStage(tasks[_id].parentProject) { checkTaskExists(_id); checkProjectExists(tasks[_id].parentProject); statusFixer(tasks[_id].parentProject); TaskManager.Task storage task = tasks[_id]; require(task.deadline > block.timestamp, "E39"); TaskManager.Submission storage submission = task.submission; submission.metadata = _metadata; submission.status = TaskManager.SubmissionStatus.Pending; }
11,607,978
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./TimedCrowdsale.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title FinalizableCrowdsale * @dev Extension of TimedCrowdsale with a one-off finalization action, where one * can do extra work after finishing. */ abstract contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() virtual internal { // solhint-disable-previous-line no-empty-blocks } }
Can be overridden to add finalization logic. The overriding function should call super._finalization() to ensure the chain of finalization is executed entirely./ solhint-disable-previous-line no-empty-blocks
function _finalization() virtual internal { }
15,866,434
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/math/SafeCast.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol) pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: Icre8ConvertV1.sol pragma solidity 0.8.11; // Learn more about the ERC20 implementation // import chainlink feeds contract Icre8ConvertV1 is Ownable, Pausable, ReentrancyGuard { // Our Token Contract IERC20 public contractToken; IERC20 public __usdtToken; AggregatorV3Interface internal priceFeed; using SafeMath for uint256; using SafeCast for uint256; using SafeERC20 for IERC20; // token price for ETH uint256 public tokensPerEth = 888; // Event that log buy operation event Icre8TokensBought(address buyer, uint256 amountOfETH, uint256 amountOfTokens); event Icre8TokensBoughtViaUSDT(address buyer, uint256 amountOfETH, uint256 amountOfTokens); event UsdtTokenFetchFailed(address senderAddress, uint256 tokenAmount); constructor(address tokenAddress, address usdtAddress, address priceFeedAddress) Ownable() Pausable() ReentrancyGuard() { contractToken = IERC20(tokenAddress); __usdtToken = IERC20(usdtAddress); priceFeed = AggregatorV3Interface(priceFeedAddress); } /** * @notice Allow users to buy tokens for ETH */ function convert() public payable whenNotPaused nonReentrant returns (uint256 tokenAmount) { require(msg.sender != address(0), "Address is zero"); require(msg.value <= 9000000000000000000 || msg.value >= 88800000000000000, "value should be between .0888 or 9 ether"); uint256 amountToBuy = ((msg.value).div(tokensPerEth)) * 100000; // check if the Vendor Contract has enough amount of tokens for the transaction require(contractToken.balanceOf(address(this)) >= amountToBuy, "Vendor contract does not enough tokens in its balance"); // Transfer token to the msg.sender contractToken.safeTransfer(msg.sender, amountToBuy); // emit the event emit Icre8TokensBought(msg.sender, msg.value, amountToBuy); return amountToBuy; } /** * @notice Allow users to sell tokens for ETH */ function buyWithUSDT(uint256 tokenAmount) public payable whenNotPaused nonReentrant { require(msg.sender != address(0), "Address is zero"); require(tokenAmount <= 5000000000 || tokenAmount >= 332000000, "Minimum 332 USDT and Max 5000 USDT"); // Transfer USDT Tether from msg.sender to contract // check for allowance if((__usdtToken).allowance(msg.sender, address(this)) >= tokenAmount) { (__usdtToken).safeTransferFrom(msg.sender, address(this), tokenAmount); } else { emit UsdtTokenFetchFailed(msg.sender, tokenAmount); } // init usdt eth price uint256 priceViaFeed = (getLatestPrice()); // finally transfer ICRE8 require(priceViaFeed > 0, "Third party vendor call failed"); uint256 calculateEth = (tokenAmount).mul(priceViaFeed).div(10 ** 18); uint256 amountToBuy = ((calculateEth).div(tokensPerEth)).mul(10 ** 17); contractToken.safeTransfer(msg.sender, amountToBuy); // require(sendTokens, "Failed to transfer tokens to user"); // emit the event emit Icre8TokensBoughtViaUSDT(msg.sender, tokenAmount, amountToBuy); } /** * @notice Allow the owner of the contract to withdraw ETH */ function withdraw() public nonReentrant onlyOwner { (bool w,) = payable(msg.sender).call{value:address(this).balance}(""); require(w); } function withdrawToken (address tokenAddress) public payable nonReentrant onlyOwner { IERC20 ___token = IERC20(tokenAddress); uint256 balance = ___token.balanceOf(address(this)); ___token.safeTransfer(payable(msg.sender), balance); } function getLatestPrice() public view returns (uint) { (,int price,,,) = priceFeed.latestRoundData(); return uint256(price); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } fallback () external payable { } receive () external payable { } }
Allow the owner of the contract to withdraw ETH/
function withdraw() public nonReentrant onlyOwner { require(w); }
11,783,799
pragma solidity ^0.4.21; // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function Owned() public { owner = msg.sender; } function changeOwner(address _newOwner) public onlyOwner{ owner = _newOwner; } } // Safe maths, borrowed from OpenZeppelin // ---------------------------------------------------------------------------- library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract ERC20Token { /* 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 public 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) public 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) public 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) public 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 public 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 ERC20Token { mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } /* Transfers tokens from your address to other */ function transfer(address _to, uint256 _value) public returns (bool success) { require (balances[msg.sender] >= _value); // Throw if sender has insufficient balance require (balances[_to] + _value >= balances[_to]); // Throw if owerflow detected balances[msg.sender] -= _value; // Deduct senders balance balances[_to] += _value; // Add recivers blaance emit Transfer(msg.sender, _to, _value); // Raise Transfer event return true; } /* Approve other address to spend tokens on your account */ function approve(address _spender, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); allowances[msg.sender][_spender] = _value; // Set allowance emit Approval(msg.sender, _spender, _value); // Raise Approval event return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); // Cast spender to tokenRecipient contract approve(_spender, _value); // Set approval to contract for _value spender.receiveApproval(msg.sender, _value, this, _extraData); // Raise method on _spender contract return true; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (balances[_from] >= _value); // Throw if sender does not have enough balance require (balances[_to] + _value >= balances[_to]); // Throw if overflow detected require (_value <= allowances[_from][msg.sender]); // Throw if you do not have allowance balances[_from] -= _value; // Deduct senders balance balances[_to] += _value; // Add recipient blaance allowances[_from][msg.sender] -= _value; // Deduct allowance for this address emit Transfer(_from, _to, _value); // Raise Transfer event return true; } /* Get the amount of allowed tokens to spend */ function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowances[_owner][_spender]; } } contract EOBIToken is standardToken,Owned { using SafeMath for uint; string public name="EOBI Token"; string public symbol="EOBI"; uint256 public decimals=18; uint256 public totalSupply = 0; uint256 public topTotalSupply = 35*10**8*10**decimals; uint256 public privateTotalSupply = percent(10); uint256 public privateSupply = 0; address public walletAddress; uint256 public exchangeRate = 10**5; bool public ICOStart; /// @dev Fallback to calling deposit when ether is sent directly to contract. function() public payable { if(ICOStart){ depositToken(msg.value); } } /// @dev initial function function EOBIToken() public { owner=msg.sender; ICOStart = true; } /// @dev calcute the tokens function percent(uint256 _percentage) internal view returns (uint256) { return _percentage.mul(topTotalSupply).div(100); } /// @dev Buys tokens with Ether. function depositToken(uint256 _value) internal { uint256 tokenAlloc = buyPriceAt() * _value; require(tokenAlloc != 0); privateSupply = privateSupply.add(tokenAlloc); require (privateSupply <= privateTotalSupply); mintTokens(msg.sender, tokenAlloc); } /// @dev Issue new tokens function mintTokens(address _to, uint256 _amount) internal { require (balances[_to] + _amount >= balances[_to]); // Check for overflows balances[_to] = balances[_to].add(_amount); // Set minted coins to target totalSupply = totalSupply.add(_amount); require(totalSupply <= topTotalSupply); emit Transfer(0x0, _to, _amount); // Create Transfer event from 0x } /// @dev Calculate exchange function buyPriceAt() internal constant returns(uint256) { return exchangeRate; } /// @dev change exchange rate function changeExchangeRate(uint256 _rate) public onlyOwner { exchangeRate = _rate; } /// @dev set initial message function setVaribles(string _name, string _symbol, uint256 _decimals) public onlyOwner { name = _name; symbol = _symbol; decimals = _decimals; topTotalSupply = 35*10**8*10**decimals; require(totalSupply <= topTotalSupply); privateTotalSupply = percent(10); require(privateSupply <= privateTotalSupply); } /// @dev change ICO State function ICOState(bool _start) public onlyOwner { ICOStart = _start; } /// @dev withDraw Ether to a Safe Wallet function withDraw(address _etherAddress) public payable onlyOwner { require (_etherAddress != address(0)); address contractAddress = this; _etherAddress.transfer(contractAddress.balance); } /// @dev allocate Token function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner { require (_owners.length == _values.length); for(uint256 i = 0; i < _owners.length ; i++){ address owner = _owners[i]; uint256 value = _values[i]; mintTokens(owner, value); } } }
change ICO State
function ICOState(bool _start) public onlyOwner { ICOStart = _start; }
2,042,846
// SPDX-License-Identifier: Apache-2.0 // Draft, example of an extended Voronoi Solidity solution, by QRUCIAL OÜ // The extension is a more fine-tuned control on the unlock controls: a more DAO-like version. // Coder: Six pragma solidity ^0.8.10; // DRAFT In this example, 4 parties (threshold = 4) out of 6 need to agree to execute the critical_impact() function // Requirement: no single account should be able to call any Major Impact function. contract Voronoi_Example { mapping (address => uint256) internal unlockers; // Address to threshold amount (single account can have multiple) mapping (uint256 => uint256) internal function_locks; // Function required to be unlocked uint256 private threshold; // Threshold for unlock event major_impact_call(bool value); // Event when a Major Impact Function is called event minor_impact_call(bool value); // Event when a Minor Impact Function is called event function_unlock(uint256 value); // Unlock event, when a function gets unlocked, unit256 -> func ID constructor() { threshold = 4; // An unlock happens when this threshold is reached or passed -> Could me more complex and each function have different threshold unlockers[msg.sender] = 22; // Add starter unlocker addresses, in this example 6 unlockers[0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2] = 10; unlockers[0xCA35b7d915458EF540aDe6068dFe2F44E8fa733c] = 25; unlockers[0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db] = 4; // unlimited number of votes? possibility to "reshare" votes all at once? //function_locks[0] = 0; // We will use structs here probably. // function id X current_vote_weight // unlocker addr X unlocker vote_weight // ++ unlocker addr X funcid X used_weight // this is go be given back after executing funcid // bit similar to "staking" // but how to remove the used_weight if votes are enough --> revoke vote func(unlockeraddr, funcid, weight_to_remove) } function unlocker_role_add(address new_unlocker) external returns (bool){ emit major_impact_call(true); require(unlockers[msg.sender] == 1); require(function_locks[0] >= threshold); unlockers[new_unlocker] = 1; return true; } function unlocker_role_remove(address rem_unlocker) external returns (bool){ emit major_impact_call(true); require(unlockers[msg.sender] == 1); require(function_locks[1] >= threshold); unlockers[rem_unlocker] = 0; // Alternative option to remove fully return true; } function unlock_voter(uint256 func_id, uint256 vote_weight) external returns (bool){ require(unlockers[msg.sender] == 1); unlockers[msg.sender] = 0; function_locks[func_id] = function_locks[func_id] + 1; return true; } // Voronoi solidity is ready to use after this. // You can add your ERC20/ERC115 or other code and use the Voronoi security functions function critical_impact1() external returns (bool) { emit major_impact_call(true); require(function_locks[2] >= threshold); function_locks[1] = 0; // Can be called only once and threshold is reset. return true; } function critical_impact2() external returns (bool) { emit major_impact_call(true); require(function_locks[3] >= threshold); function_locks[2] = 0; // Can be called only once and threshold is reset. return true; } function minor_impact() external returns (bool) { // No unlock check, just execute emit minor_impact_call(true); return true; } }
Unlock event, when a function gets unlocked, unit256 -> func ID
event function_unlock(uint256 value);
12,815,517
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; abstract contract Context { function _MSGSENDER442() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA841() 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; } } 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 _ADD793(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING if (!_CONTAINS602(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 _REMOVE671(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 _CONTAINS602(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING return set._indexes[value] != 0; } function _LENGTH966(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING return set._values.length; } function _AT186(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 ADD955(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD793(set._inner, bytes32(uint256(value))); } function REMOVE612(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE671(set._inner, bytes32(uint256(value))); } function CONTAINS582(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS602(set._inner, bytes32(uint256(value))); } function LENGTH322(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH966(set._inner); } function AT372(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING return address(uint256(_AT186(set._inner, index))); } // UintSet struct UintSet { Set _inner; } function ADD955(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _ADD793(set._inner, bytes32(value)); } function REMOVE612(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING return _REMOVE671(set._inner, bytes32(value)); } function CONTAINS582(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING return _CONTAINS602(set._inner, bytes32(value)); } function LENGTH322(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING return _LENGTH966(set._inner); } function AT372(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING return uint256(_AT186(set._inner, index)); } } library SafeMath { function ADD955(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB444(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB444(a, b, "SafeMath: subtraction overflow"); } function SUB444(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 MUL509(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 DIV140(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV140(a, b, "SafeMath: division by zero"); } function DIV140(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD127(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD127(a, b, "SafeMath: modulo by zero"); } function MOD127(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } contract Pausable is Context { event PAUSED925(address account); //inject NONSTANDARD NAMING event UNPAUSED624(address account); //inject NONSTANDARD NAMING bool private _paused; constructor () internal { _paused = false; } function PAUSED303() public view returns (bool) { //inject NONSTANDARD NAMING return _paused; } modifier WHENNOTPAUSED156() { //inject NONSTANDARD NAMING require(!_paused, "Pausable: paused"); _; } modifier WHENPAUSED81() { //inject NONSTANDARD NAMING require(_paused, "Pausable: not paused"); _; } function _PAUSE21() internal virtual WHENNOTPAUSED156 { //inject NONSTANDARD NAMING _paused = true; emit PAUSED925(_MSGSENDER442()); } function _UNPAUSE943() internal virtual WHENPAUSED81 { //inject NONSTANDARD NAMING _paused = false; emit UNPAUSED624(_MSGSENDER442()); } } 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_role643 = 0x00; //inject NONSTANDARD NAMING event ROLEADMINCHANGED358(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING event ROLEGRANTED844(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING event ROLEREVOKED840(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING function HASROLE566(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING return _roles[role].members.CONTAINS582(account); } function GETROLEMEMBERCOUNT266(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING return _roles[role].members.LENGTH322(); } function GETROLEMEMBER390(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING return _roles[role].members.AT372(index); } function GETROLEADMIN142(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING return _roles[role].adminRole; } function GRANTROLE448(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE566(_roles[role].adminRole, _MSGSENDER442()), "AccessControl: sender must be an admin to grant"); _GRANTROLE994(role, account); } function REVOKEROLE161(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(HASROLE566(_roles[role].adminRole, _MSGSENDER442()), "AccessControl: sender must be an admin to revoke"); _REVOKEROLE858(role, account); } function RENOUNCEROLE414(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING require(account == _MSGSENDER442(), "AccessControl: can only renounce roles for self"); _REVOKEROLE858(role, account); } function _SETUPROLE604(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING _GRANTROLE994(role, account); } function _SETROLEADMIN339(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING emit ROLEADMINCHANGED358(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _GRANTROLE994(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.ADD955(account)) { emit ROLEGRANTED844(role, account, _MSGSENDER442()); } } function _REVOKEROLE858(bytes32 role, address account) private { //inject NONSTANDARD NAMING if (_roles[role].members.REMOVE612(account)) { emit ROLEREVOKED840(role, account, _MSGSENDER442()); } } } library Address { function ISCONTRACT149(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE745(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"); } function FUNCTIONCALL287(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL287(target, data, "Address: low-level call failed"); } function FUNCTIONCALL287(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE197(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE757(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE757(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE757(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE197(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE197(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT149(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); } } } } interface IERC20 { function NAME653() external view returns (string memory); //inject NONSTANDARD NAMING function SYMBOL206() external view returns (string memory); //inject NONSTANDARD NAMING function DECIMALS526() external view returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY875() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF638(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE195(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER72(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE120(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM500( //inject NONSTANDARD NAMING address from, address to, uint value ) external returns (bool); event TRANSFER974(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL68(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract LnAdmin { address public admin; address public candidate; constructor(address _admin) public { require(_admin != address(0), "admin address cannot be 0"); admin = _admin; emit ADMINCHANGED70(address(0), _admin); } function SETCANDIDATE399(address _candidate) external ONLYADMIN30 { //inject NONSTANDARD NAMING address old = candidate; candidate = _candidate; emit CANDIDATECHANGED218( old, candidate); } function BECOMEADMIN406( ) external { //inject NONSTANDARD NAMING require( msg.sender == candidate, "Only candidate can become admin"); address old = admin; admin = candidate; emit ADMINCHANGED70( old, admin ); } modifier ONLYADMIN30 { //inject NONSTANDARD NAMING require( (msg.sender == admin), "Only the contract admin can perform this action"); _; } event CANDIDATECHANGED218(address oldCandidate, address newCandidate ); //inject NONSTANDARD NAMING event ADMINCHANGED70(address oldAdmin, address newAdmin); //inject NONSTANDARD NAMING } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals39 = 18; //inject NONSTANDARD NAMING uint8 public constant highprecisiondecimals272 = 27; //inject NONSTANDARD NAMING uint public constant unit739 = 10**uint(decimals39); //inject NONSTANDARD NAMING uint public constant precise_unit766 = 10**uint(highprecisiondecimals272); //inject NONSTANDARD NAMING uint private constant unit_to_high_precision_conversion_factor241 = 10**uint(highprecisiondecimals272 - decimals39); //inject NONSTANDARD NAMING function UNIT5() external pure returns (uint) { //inject NONSTANDARD NAMING return unit739; } function PRECISEUNIT401() external pure returns (uint) { //inject NONSTANDARD NAMING return precise_unit766; } function MULTIPLYDECIMAL731(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return x.MUL509(y) / unit739; } function _MULTIPLYDECIMALROUND367( //inject NONSTANDARD NAMING uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint quotientTimesTen = x.MUL509(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function MULTIPLYDECIMALROUNDPRECISE456(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _MULTIPLYDECIMALROUND367(x, y, precise_unit766); } function MULTIPLYDECIMALROUND81(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _MULTIPLYDECIMALROUND367(x, y, unit739); } function DIVIDEDECIMAL852(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return x.MUL509(unit739).DIV140(y); } function _DIVIDEDECIMALROUND630( //inject NONSTANDARD NAMING uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.MUL509(precisionUnit * 10).DIV140(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function DIVIDEDECIMALROUND74(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _DIVIDEDECIMALROUND630(x, y, unit739); } function DIVIDEDECIMALROUNDPRECISE587(uint x, uint y) internal pure returns (uint) { //inject NONSTANDARD NAMING return _DIVIDEDECIMALROUND630(x, y, precise_unit766); } function DECIMALTOPRECISEDECIMAL237(uint i) internal pure returns (uint) { //inject NONSTANDARD NAMING return i.MUL509(unit_to_high_precision_conversion_factor241); } function PRECISEDECIMALTODECIMAL159(uint i) internal pure returns (uint) { //inject NONSTANDARD NAMING uint quotientTimesTen = i / (unit_to_high_precision_conversion_factor241 / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } interface ILinearStaking { function STAKING189(uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function CANCELSTAKING166(uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function CLAIM668() external returns (bool); //inject NONSTANDARD NAMING function STAKINGBALANCEOF960(address account) external view returns(uint256); //inject NONSTANDARD NAMING } contract LnLinearStakingStorage is LnAdmin { using SafeMath for uint256; LnAccessControl public accessCtrl; bytes32 public constant data_access_role516 = "LinearStakingStorage"; //inject NONSTANDARD NAMING struct StakingData { uint256 amount; uint256 staketime; } mapping (address => StakingData[]) public stakesdata; mapping (uint256 => uint256) public weeksTotal; // week staking amount uint256 public stakingStartTime = 1600329600; // TODO: UTC or UTC+8 uint256 public stakingEndTime = 1605168000; uint256 public totalWeekNumber = 8; uint256 public weekRewardAmount = 18750000e18; constructor(address _admin, address _accessCtrl) public LnAdmin(_admin) { accessCtrl = LnAccessControl(_accessCtrl); } modifier ONLYLINEARSTAKINGSTORAGEROLE421(address _address) { //inject NONSTANDARD NAMING require(accessCtrl.HASROLE566(data_access_role516, _address), "Only Linear Staking Storage Role"); _; } function SETACCESSCONTROL240(address _accessCtrl) external ONLYADMIN30 { //inject NONSTANDARD NAMING accessCtrl = LnAccessControl(_accessCtrl); } function WEEKTOTALSTAKING870() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING uint256[] memory totals = new uint256[](totalWeekNumber); for (uint256 i=0; i< totalWeekNumber; i++) { uint256 delta = weeksTotal[i]; if (i == 0) { totals[i] = delta; } else { totals[i] = totals[i-1].ADD955(delta); } } return totals; } function GETSTAKESDATALENGTH308(address account) external view returns(uint256) { //inject NONSTANDARD NAMING return stakesdata[account].length; } function GETSTAKESDATABYINDEX845(address account, uint256 index) external view returns(uint256, uint256) { //inject NONSTANDARD NAMING return (stakesdata[account][index].amount, stakesdata[account][index].staketime); } function STAKINGBALANCEOF960(address account) external view returns(uint256) { //inject NONSTANDARD NAMING uint256 total = 0; StakingData[] memory stakes = stakesdata[account]; for (uint256 i=0; i < stakes.length; i++) { total = total.ADD955(stakes[i].amount); } return total; } function REQUIREINSTAKINGPERIOD293() external view { //inject NONSTANDARD NAMING require(stakingStartTime < block.timestamp, "Staking not start"); require(block.timestamp < stakingEndTime, "Staking stage has end."); } function REQUIRESTAKINGEND294() external view { //inject NONSTANDARD NAMING require(block.timestamp > stakingEndTime, "Need wait to staking end"); } function PUSHSTAKINGDATA192(address account, uint256 amount, uint256 staketime) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING LnLinearStakingStorage.StakingData memory data = LnLinearStakingStorage.StakingData({ amount: amount, staketime: staketime }); stakesdata[account].push(data); } function STAKINGDATAADD553(address account, uint256 index, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account][index].amount = stakesdata[account][index].amount.ADD955(amount); } function STAKINGDATASUB735(address account, uint256 index, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account][index].amount = stakesdata[account][index].amount.SUB444(amount, "StakingDataSub sub overflow"); } function DELETESTAKESDATA62(address account) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING delete stakesdata[account]; } function POPSTAKESDATA423(address account) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING stakesdata[account].pop(); } function ADDWEEKSTOTAL472(uint256 staketime, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING uint256 weekNumber = staketime.SUB444(stakingStartTime, "AddWeeksTotal sub overflow") / 1 weeks; weeksTotal[weekNumber] = weeksTotal[weekNumber].ADD955(amount); } function SUBWEEKSTOTAL597(uint256 staketime, uint256 amount) external ONLYLINEARSTAKINGSTORAGEROLE421(msg.sender) { //inject NONSTANDARD NAMING uint256 weekNumber = staketime.SUB444(stakingStartTime, "SubWeeksTotal weekNumber sub overflow") / 1 weeks; weeksTotal[weekNumber] = weeksTotal[weekNumber].SUB444(amount, "SubWeeksTotal weeksTotal sub overflow"); } function SETWEEKREWARDAMOUNT481(uint256 _weekRewardAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING weekRewardAmount = _weekRewardAmount; } function SETSTAKINGPERIOD256(uint _stakingStartTime, uint _stakingEndTime) external ONLYADMIN30 { //inject NONSTANDARD NAMING require(_stakingEndTime > _stakingStartTime); stakingStartTime = _stakingStartTime; stakingEndTime = _stakingEndTime; totalWeekNumber = stakingEndTime.SUB444(stakingStartTime, "setStakingPeriod totalWeekNumber sub overflow") / 1 weeks; if (stakingEndTime.SUB444(stakingStartTime, "setStakingPeriod stakingEndTime sub overflow") % 1 weeks != 0) { totalWeekNumber = totalWeekNumber.ADD955(1); } } } contract LnLinearStaking is LnAdmin, Pausable, ILinearStaking { using SafeMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; constructor( address _admin, address _linaToken, address _storage ) public LnAdmin(_admin) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETLINATOKENADDRESS568(address _token) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_token); } function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) external override view returns(uint256) { //inject NONSTANDARD NAMING return stakingStorage.STAKINGBALANCEOF960(account); } function GETSTAKESDATALENGTH308(address account) external view returns(uint256) { //inject NONSTANDARD NAMING return stakingStorage.GETSTAKESDATALENGTH308(account); } //-------------------------------------------------------- function STAKING189(uint256 amount) public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount >= minStakingAmount, "Staking amount too small."); require(stakingStorage.GETSTAKESDATALENGTH308(msg.sender) < accountStakingListLimit, "Staking list out of limit."); //linaToken.burn(msg.sender, amount); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); stakingStorage.PUSHSTAKINGDATA192(msg.sender, amount, block.timestamp); stakingStorage.ADDWEEKSTOTAL472(block.timestamp, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function CANCELSTAKING166(uint256 amount) public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount > 0, "Invalid amount."); uint256 returnToken = amount; for (uint256 i = stakingStorage.GETSTAKESDATALENGTH308(msg.sender); i >= 1 ; i--) { (uint256 stakingAmount, uint256 staketime) = stakingStorage.GETSTAKESDATABYINDEX845(msg.sender, i-1); if (amount >= stakingAmount) { amount = amount.SUB444(stakingAmount, "cancelStaking sub overflow"); stakingStorage.POPSTAKESDATA423(msg.sender); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(msg.sender, i-1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); amount = 0; } if (amount == 0) break; } require(amount == 0, "Cancel amount too big then staked."); //linaToken.mint(msg.sender, returnToken); linaToken.TRANSFER72(msg.sender, returnToken); emit CANCELSTAKING945(msg.sender, returnToken); return true; } // claim reward // Note: 111111111token111 function CLAIM668() public WHENNOTPAUSED156 override returns (bool) { //inject NONSTANDARD NAMING stakingStorage.REQUIRESTAKINGEND294(); require(stakingStorage.GETSTAKESDATALENGTH308(msg.sender) > 0, "Nothing to claim"); uint256 totalWeekNumber = stakingStorage.totalWeekNumber(); uint256 totalStaking = 0; uint256 totalReward = 0; uint256[] memory finalTotals = stakingStorage.WEEKTOTALSTAKING870(); for (uint256 i=0; i < stakingStorage.GETSTAKESDATALENGTH308(msg.sender); i++) { (uint256 stakingAmount, uint256 staketime) = stakingStorage.GETSTAKESDATABYINDEX845(msg.sender, i); uint256 stakedWeedNumber = staketime.SUB444(stakingStorage.stakingStartTime(), "claim sub overflow") / 1 weeks; totalStaking = totalStaking.ADD955(stakingAmount); uint256 reward = 0; for (uint256 j=stakedWeedNumber; j < totalWeekNumber; j++) { reward = reward.ADD955( stakingAmount.MUL509(precision_uint99).DIV140(finalTotals[j]) ); //move .mul(weekRewardAmount) to next line. } reward = reward.MUL509(stakingStorage.weekRewardAmount()).DIV140(precision_uint99); totalReward = totalReward.ADD955( reward ); } stakingStorage.DELETESTAKESDATA62(msg.sender); //linaToken.mint(msg.sender, totalStaking.add(totalReward) ); linaToken.TRANSFER72(msg.sender, totalStaking.ADD955(totalReward) ); emit CLAIM827(msg.sender, totalReward, totalStaking); return true; } } // example: //LnAccessControl accessCtrl = LnAccessControl(addressStorage.getAddress("LnAccessControl")); //require(accessCtrl.hasRole(accessCtrl.DEBT_SYSTEM(), _address), "Need debt system access role"); // contract access control contract LnAccessControl is AccessControl { using Address for address; // ------------------------------------------------------- // role type bytes32 public constant issue_asset_role354 = ("ISSUE_ASSET"); //keccak256 //inject NONSTANDARD NAMING bytes32 public constant burn_asset_role864 = ("BURN_ASSET"); //inject NONSTANDARD NAMING bytes32 public constant debt_system916 = ("LnDebtSystem"); //inject NONSTANDARD NAMING // ------------------------------------------------------- constructor(address admin) public { _SETUPROLE604(default_admin_role643, admin); } function ISADMIN537(address _address) public view returns (bool) { //inject NONSTANDARD NAMING return HASROLE566(default_admin_role643, _address); } function SETADMIN420(address _address) public returns (bool) { //inject NONSTANDARD NAMING require(ISADMIN537(msg.sender), "Only admin"); _SETUPROLE604(default_admin_role643, _address); } // ------------------------------------------------------- // this func need admin role. grantRole and revokeRole need admin role function SETROLES11(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) external { //inject NONSTANDARD NAMING require(ISADMIN537(msg.sender), "Only admin"); _SETROLES348(roleType, addresses, setTo); } function _SETROLES348(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) private { //inject NONSTANDARD NAMING require(addresses.length == setTo.length, "parameter address length not eq"); for (uint256 i=0; i < addresses.length; i++) { //require(addresses[i].isContract(), "Role address need contract only"); if (setTo[i]) { GRANTROLE448(roleType, addresses[i]); } else { REVOKEROLE161(roleType, addresses[i]); } } } // function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) public { // _setRoles(roleType, addresses, setTo); // } // Issue burn function SETISSUEASSETROLE734(address[] calldata issuer, bool[] calldata setTo) public { //inject NONSTANDARD NAMING _SETROLES348(issue_asset_role354, issuer, setTo); } function SETBURNASSETROLE582(address[] calldata burner, bool[] calldata setTo) public { //inject NONSTANDARD NAMING _SETROLES348(burn_asset_role864, burner, setTo); } // function SETDEBTSYSTEMROLE518(address[] calldata _address, bool[] calldata _setTo) public { //inject NONSTANDARD NAMING _SETROLES348(debt_system916, _address, _setTo); } } abstract contract LnOperatorModifier is LnAdmin { address public operator; constructor(address _operator) internal { require(admin != address(0), "admin must be set"); operator = _operator; emit OPERATORUPDATED731(_operator); } function SETOPERATOR821(address _opperator) external ONLYADMIN30 { //inject NONSTANDARD NAMING operator = _opperator; emit OPERATORUPDATED731(_opperator); } modifier ONLYOPERATOR997() { //inject NONSTANDARD NAMING require(msg.sender == operator, "Only operator can perform this action"); _; } event OPERATORUPDATED731(address operator); //inject NONSTANDARD NAMING } contract LnRewardCalculator { using SafeMath for uint256; struct UserInfo { uint256 reward; uint256 amount; uint256 rewardDebt; } struct PoolInfo { uint256 amount; uint256 lastRewardBlock; uint256 accRewardPerShare; } uint256 public rewardPerBlock; PoolInfo public mPoolInfo; mapping(address => UserInfo) public userInfo; uint256 public startBlock; uint256 public remainReward; uint256 public accReward; constructor(uint256 _rewardPerBlock, uint256 _startBlock) public { rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; mPoolInfo.lastRewardBlock = startBlock; } function _CALCREWARD319(uint256 curBlock, address _user) //inject NONSTANDARD NAMING internal view returns (uint256) { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.amount; if (curBlock > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "cr curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); accRewardPerShare = accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); } uint256 newReward = user.amount.MUL509(accRewardPerShare).DIV140(1e20).SUB444( user.rewardDebt, "cr newReward sub overflow" ); return newReward.ADD955(user.reward); } function REWARDOF391(address _user) public view returns (uint256) { //inject NONSTANDARD NAMING return userInfo[_user].reward; } function AMOUNT622() public view returns (uint256) { //inject NONSTANDARD NAMING return mPoolInfo.amount; } function AMOUNTOF525(address _user) public view returns (uint256) { //inject NONSTANDARD NAMING return userInfo[_user].amount; } function GETUSERINFO565(address _user) //inject NONSTANDARD NAMING public view returns ( uint256, uint256, uint256 ) { return ( userInfo[_user].reward, userInfo[_user].amount, userInfo[_user].rewardDebt ); } function GETPOOLINFO789() //inject NONSTANDARD NAMING public view returns ( uint256, uint256, uint256 ) { return ( mPoolInfo.amount, mPoolInfo.lastRewardBlock, mPoolInfo.accRewardPerShare ); } function _UPDATE589(uint256 curBlock) internal { //inject NONSTANDARD NAMING PoolInfo storage pool = mPoolInfo; if (curBlock <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.amount; if (lpSupply == 0) { pool.lastRewardBlock = curBlock; return; } uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "_update curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); remainReward = remainReward.ADD955(curReward); accReward = accReward.ADD955(curReward); pool.accRewardPerShare = pool.accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); pool.lastRewardBlock = curBlock; } function _DEPOSIT6( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) internal { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_addr]; _UPDATE589(curBlock); if (user.amount > 0) { uint256 pending = user .amount .MUL509(pool.accRewardPerShare) .DIV140(1e20) .SUB444(user.rewardDebt, "_deposit pending sub overflow"); if (pending > 0) { REWARD327(user, pending); } } if (_amount > 0) { user.amount = user.amount.ADD955(_amount); pool.amount = pool.amount.ADD955(_amount); } user.rewardDebt = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20); } function _WITHDRAW71( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) internal { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_addr]; require(user.amount >= _amount, "_withdraw: not good"); _UPDATE589(curBlock); uint256 pending = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20).SUB444( user.rewardDebt, "_withdraw pending sub overflow" ); if (pending > 0) { REWARD327(user, pending); } if (_amount > 0) { user.amount = user.amount.SUB444( _amount, "_withdraw user.amount sub overflow" ); pool.amount = pool.amount.SUB444( _amount, "_withdraw pool.amount sub overflow" ); } user.rewardDebt = user.amount.MUL509(pool.accRewardPerShare).DIV140(1e20); } function REWARD327(UserInfo storage user, uint256 _amount) internal { //inject NONSTANDARD NAMING if (_amount > remainReward) { _amount = remainReward; } remainReward = remainReward.SUB444( _amount, "reward remainReward sub overflow" ); user.reward = user.reward.ADD955(_amount); } function _CLAIM850(address _addr) internal { //inject NONSTANDARD NAMING UserInfo storage user = userInfo[_addr]; if (user.reward > 0) { user.reward = 0; } } } contract LnRewardCalculatorTest is LnRewardCalculator { constructor(uint256 _rewardPerBlock, uint256 _startBlock) public LnRewardCalculator(_rewardPerBlock, _startBlock) {} function DEPOSIT888( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) public { _DEPOSIT6(curBlock, _addr, _amount); } function WITHDRAW713( //inject NONSTANDARD NAMING uint256 curBlock, address _addr, uint256 _amount ) public { _WITHDRAW71(curBlock, _addr, _amount); } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARD319(curBlock, _user); } } contract LnSimpleStaking is LnAdmin, Pausable, ILinearStaking, LnRewardCalculator { using SafeMath for uint256; using SafeDecimalMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; uint256 public mEndBlock; address public mOldStaking; uint256 public mOldAmount; uint256 public mWidthdrawRewardFromOldStaking; uint256 public claimRewardLockTime = 1620806400; // 2021-5-12 address public mTargetAddress; uint256 public mTransLockTime; mapping(address => uint256) public mOldReward; constructor( address _admin, address _linaToken, address _storage, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock ) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); mEndBlock = _endBlock; } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint256 staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING event TRANSLOCK726(address target, uint256 time); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) //inject NONSTANDARD NAMING external override view returns (uint256) { uint256 stakingBalance = super.AMOUNTOF525(account).ADD955( stakingStorage.STAKINGBALANCEOF960(account) ); return stakingBalance; } function GETSTAKESDATALENGTH308(address account) //inject NONSTANDARD NAMING external view returns (uint256) { return stakingStorage.GETSTAKESDATALENGTH308(account); } //-------------------------------------------------------- function MIGRATIONSOLDSTAKING766( //inject NONSTANDARD NAMING address contractAddr, uint256 amount, uint256 blockNb ) public ONLYADMIN30 { super._DEPOSIT6(blockNb, contractAddr, amount); mOldStaking = contractAddr; mOldAmount = amount; } function STAKING189(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { stakingStorage.REQUIREINSTAKINGPERIOD293(); require(amount >= minStakingAmount, "Staking amount too small."); //require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } super._DEPOSIT6(blockNb, msg.sender, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function _WIDTHDRAWFROMOLDSTAKING790(address _addr, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); super._WITHDRAW71(blockNb, mOldStaking, amount); // sub already withraw reward, then cal portion uint256 reward = super .REWARDOF391(mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "_widthdrawFromOldStaking reward sub overflow" ) .MUL509(amount) .MUL509(1e20) .DIV140(oldStakingAmount) .DIV140(1e20); mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.ADD955( reward ); mOldReward[_addr] = mOldReward[_addr].ADD955(reward); } function _CANCELSTAKING147(address user, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 returnAmount = amount; uint256 newAmount = super.AMOUNTOF525(user); if (newAmount >= amount) { super._WITHDRAW71(blockNb, user, amount); amount = 0; } else { if (newAmount > 0) { super._WITHDRAW71(blockNb, user, newAmount); amount = amount.SUB444( newAmount, "_cancelStaking amount sub overflow" ); } for ( uint256 i = stakingStorage.GETSTAKESDATALENGTH308(user); i >= 1; i-- ) { (uint256 stakingAmount, uint256 staketime) = stakingStorage .GETSTAKESDATABYINDEX845(user, i - 1); if (amount >= stakingAmount) { amount = amount.SUB444( stakingAmount, "_cancelStaking amount sub overflow" ); stakingStorage.POPSTAKESDATA423(user); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); _WIDTHDRAWFROMOLDSTAKING790(user, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(user, i - 1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); _WIDTHDRAWFROMOLDSTAKING790(user, amount); amount = 0; } if (amount == 0) break; } } // cancel as many as possible, not fail, that waste gas //require(amount == 0, "Cancel amount too big then staked."); linaToken.TRANSFER72(msg.sender, returnAmount.SUB444(amount)); } function CANCELSTAKING166(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { //stakingStorage.requireInStakingPeriod(); require(amount > 0, "Invalid amount."); _CANCELSTAKING147(msg.sender, amount); emit CANCELSTAKING945(msg.sender, amount); return true; } function GETTOTALREWARD238(uint256 blockNb, address _user) //inject NONSTANDARD NAMING public view returns (uint256 total) { if (blockNb > mEndBlock) { blockNb = mEndBlock; } // 1111111111 // 1,1111111cancel11 // 2,1111111 // 31111111 total = mOldReward[_user]; uint256 iMyOldStaking = 0; for ( uint256 i = 0; i < stakingStorage.GETSTAKESDATALENGTH308(_user); i++ ) { (uint256 stakingAmount, ) = stakingStorage.GETSTAKESDATABYINDEX845( _user, i ); iMyOldStaking = iMyOldStaking.ADD955(stakingAmount); } if (iMyOldStaking > 0) { uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); uint256 iReward2 = super ._CALCREWARD319(blockNb, mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "getTotalReward iReward2 sub overflow" ) .MUL509(iMyOldStaking) .DIV140(oldStakingAmount); total = total.ADD955(iReward2); } uint256 reward3 = super._CALCREWARD319(blockNb, _user); total = total.ADD955(reward3); } // claim reward // Note: 111111111token111 function CLAIM668() public override WHENNOTPAUSED156 returns (bool) { //inject NONSTANDARD NAMING //stakingStorage.requireStakingEnd(); require( block.timestamp > claimRewardLockTime, "Not time to claim reward" ); uint256 iMyOldStaking = stakingStorage.STAKINGBALANCEOF960(msg.sender); uint256 iAmount = super.AMOUNTOF525(msg.sender); _CANCELSTAKING147(msg.sender, iMyOldStaking.ADD955(iAmount)); uint256 iReward = GETTOTALREWARD238(mEndBlock, msg.sender); _CLAIM850(msg.sender); mOldReward[msg.sender] = 0; linaToken.TRANSFER72(msg.sender, iReward); emit CLAIM827(msg.sender, iReward, iMyOldStaking.ADD955(iAmount)); return true; } function SETREWARDLOCKTIME580(uint256 newtime) public ONLYADMIN30 { //inject NONSTANDARD NAMING claimRewardLockTime = newtime; } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARD319(curBlock, _user); } function SETTRANSLOCK553(address target, uint256 locktime) public ONLYADMIN30 { //inject NONSTANDARD NAMING require( locktime >= now + 2 days, "locktime need larger than cur time 2 days" ); mTargetAddress = target; mTransLockTime = locktime; emit TRANSLOCK726(mTargetAddress, mTransLockTime); } function TRANSTOKENS575(uint256 amount) public ONLYADMIN30 { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); linaToken.TRANSFER72(mTargetAddress, amount); } } contract HelperPushStakingData is LnAdmin { constructor(address _admin) public LnAdmin(_admin) {} function PUSHSTAKINGDATA192( //inject NONSTANDARD NAMING address _storage, address[] calldata account, uint256[] calldata amount, uint256[] calldata staketime ) external { require(account.length > 0, "array length zero"); require(account.length == amount.length, "array length not eq"); require(account.length == staketime.length, "array length not eq"); LnLinearStakingStorage stakingStorage = LnLinearStakingStorage( _storage ); for (uint256 i = 0; i < account.length; i++) { stakingStorage.PUSHSTAKINGDATA192(account[i], amount[i], staketime[i]); stakingStorage.ADDWEEKSTOTAL472(staketime[i], amount[i]); } } //unstaking. } contract MultiSigForTransferFunds { mapping(address => uint256) public mAdmins; uint256 public mConfirmNumb; uint256 public mProposalNumb; uint256 public mAmount; LnSimpleStaking public mStaking; address[] public mAdminArr; uint256 public mTransLockTime; constructor( address[] memory _addr, uint256 iConfirmNumb, LnSimpleStaking _staking ) public { for (uint256 i = 0; i < _addr.length; ++i) { mAdmins[_addr[i]] = 1; } mConfirmNumb = iConfirmNumb; mProposalNumb = 0; mStaking = _staking; mAdminArr = _addr; } function BECOMEADMIN406(address target) external { //inject NONSTANDARD NAMING LnAdmin(target).BECOMEADMIN406(); } function SETTRANSLOCK553( //inject NONSTANDARD NAMING address target, uint256 locktime, uint256 amount ) public { require(mAdmins[msg.sender] == 1, "not in admin list or set state"); _RESET370(); mStaking.SETTRANSLOCK553(target, locktime); mAmount = amount; mProposalNumb = 1; mAdmins[msg.sender] = 2; // mTransLockTime = locktime; } // call this when the locktime expired function CONFIRMTRANSFER169() public { //inject NONSTANDARD NAMING require(mAdmins[msg.sender] == 1, "not in admin list or set state"); mProposalNumb = mProposalNumb + 1; mAdmins[msg.sender] = 2; } function DOTRANSFER874() public { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); require(mProposalNumb >= mConfirmNumb, "need more confirm"); _RESET370(); mStaking.TRANSTOKENS575(mAmount); } function _RESET370() internal { //inject NONSTANDARD NAMING mProposalNumb = 0; mTransLockTime = 0; // reset for (uint256 i = 0; i < mAdminArr.length; ++i) { mAdmins[mAdminArr[i]] = 1; } } } contract LnSimpleStakingExtension is LnAdmin, Pausable, ILinearStaking, LnRewardCalculator { using SafeMath for uint256; using SafeDecimalMath for uint256; IERC20 public linaToken; // lina token proxy address LnLinearStakingStorage public stakingStorage; uint256 public mEndBlock; address public mOldStaking; uint256 public mOldAmount; uint256 public mWidthdrawRewardFromOldStaking; uint256 public claimRewardLockTime = 1620806400; // 2021-5-12 address public mTargetAddress; uint256 public mTransLockTime; LnSimpleStaking public mOldSimpleStaking; bool public requireSync = false; mapping(address => uint256) public mOldReward; mapping(address => bool) public syncUserInfo; constructor( address _admin, address _linaToken, address _storage, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _endBlock, address _mOldSimpleStaking ) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) { linaToken = IERC20(_linaToken); stakingStorage = LnLinearStakingStorage(_storage); mEndBlock = _endBlock; if (_mOldSimpleStaking != address(0)) { mOldSimpleStaking = LnSimpleStaking(_mOldSimpleStaking); ( mPoolInfo.amount, , mPoolInfo.accRewardPerShare ) = mOldSimpleStaking.GETPOOLINFO789(); requireSync = true; } } function SETLINATOKEN908(address _linaToken) external ONLYADMIN30 { //inject NONSTANDARD NAMING linaToken = IERC20(_linaToken); } function SETPAUSED644(bool _paused) external ONLYADMIN30 { //inject NONSTANDARD NAMING if (_paused) { _PAUSE21(); } else { _UNPAUSE943(); } } event STAKING625(address indexed who, uint256 value, uint256 staketime); //inject NONSTANDARD NAMING event CANCELSTAKING945(address indexed who, uint256 value); //inject NONSTANDARD NAMING event CLAIM827(address indexed who, uint256 rewardval, uint256 totalStaking); //inject NONSTANDARD NAMING event TRANSLOCK726(address target, uint256 time); //inject NONSTANDARD NAMING uint256 public accountStakingListLimit = 50; uint256 public minStakingAmount = 1e18; // 1 token uint256 public constant precision_uint99 = 1e23; //inject NONSTANDARD NAMING function SETSTAKINGLISTLIMIT246(uint256 _limit) external ONLYADMIN30 { //inject NONSTANDARD NAMING accountStakingListLimit = _limit; } function SETMINSTAKINGAMOUNT66(uint256 _minStakingAmount) external ONLYADMIN30 { //inject NONSTANDARD NAMING minStakingAmount = _minStakingAmount; } function STAKINGBALANCEOF960(address account) //inject NONSTANDARD NAMING external override view returns (uint256) { uint256 stakingBalance = super.AMOUNTOF525(account).ADD955( stakingStorage.STAKINGBALANCEOF960(account) ); return stakingBalance; } function GETSTAKESDATALENGTH308(address account) //inject NONSTANDARD NAMING external view returns (uint256) { return stakingStorage.GETSTAKESDATALENGTH308(account); } function SETENDBLOCK987(uint256 _newEndBlock) external ONLYADMIN30 { //inject NONSTANDARD NAMING require( _newEndBlock > mEndBlock, "new endBlock less than old endBlock." ); mEndBlock = _newEndBlock; } // function isUserSynced(address _user) internal view returns (bool) { // bool status; // if (!requireSync) { // status = true; // } else { // status = syncUserInfo[_user]; // } // return status; // } function SYNCUSERINFODATA21(address _user) internal { //inject NONSTANDARD NAMING if (requireSync && !syncUserInfo[_user]) { ( userInfo[_user].reward, userInfo[_user].amount, userInfo[_user].rewardDebt ) = mOldSimpleStaking.GETUSERINFO565(_user); syncUserInfo[_user] = true; } } //-------------------------------------------------------- function MIGRATIONSOLDSTAKING766( //inject NONSTANDARD NAMING address contractAddr, uint256 amount, uint256 blockNb ) public ONLYADMIN30 { super._DEPOSIT6(blockNb, contractAddr, amount); mOldStaking = contractAddr; mOldAmount = amount; } function STAKING189(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { // stakingStorage.requireInStakingPeriod(); // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } require(amount >= minStakingAmount, "Staking amount too small."); //require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); linaToken.TRANSFERFROM500(msg.sender, address(this), amount); uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } super._DEPOSIT6(blockNb, msg.sender, amount); emit STAKING625(msg.sender, amount, block.timestamp); return true; } function _WIDTHDRAWFROMOLDSTAKING790(address _addr, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); super._WITHDRAW71(blockNb, mOldStaking, amount); // sub already withraw reward, then cal portion uint256 reward = super .REWARDOF391(mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "_widthdrawFromOldStaking reward sub overflow" ) .MUL509(amount) .MUL509(1e20) .DIV140(oldStakingAmount) .DIV140(1e20); mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.ADD955( reward ); mOldReward[_addr] = mOldReward[_addr].ADD955(reward); } function _CANCELSTAKING147(address user, uint256 amount) internal { //inject NONSTANDARD NAMING uint256 blockNb = block.number; if (blockNb > mEndBlock) { blockNb = mEndBlock; } uint256 returnAmount = amount; uint256 newAmount = super.AMOUNTOF525(user); if (newAmount >= amount) { super._WITHDRAW71(blockNb, user, amount); amount = 0; } else { if (newAmount > 0) { super._WITHDRAW71(blockNb, user, newAmount); amount = amount.SUB444( newAmount, "_cancelStaking amount sub overflow" ); } for ( uint256 i = stakingStorage.GETSTAKESDATALENGTH308(user); i >= 1; i-- ) { (uint256 stakingAmount, uint256 staketime) = stakingStorage .GETSTAKESDATABYINDEX845(user, i - 1); if (amount >= stakingAmount) { amount = amount.SUB444( stakingAmount, "_cancelStaking amount sub overflow" ); stakingStorage.POPSTAKESDATA423(user); stakingStorage.SUBWEEKSTOTAL597(staketime, stakingAmount); _WIDTHDRAWFROMOLDSTAKING790(user, stakingAmount); } else { stakingStorage.STAKINGDATASUB735(user, i - 1, amount); stakingStorage.SUBWEEKSTOTAL597(staketime, amount); _WIDTHDRAWFROMOLDSTAKING790(user, amount); amount = 0; } if (amount == 0) break; } } // cancel as many as possible, not fail, that waste gas //require(amount == 0, "Cancel amount too big then staked."); linaToken.TRANSFER72(msg.sender, returnAmount.SUB444(amount)); } function CANCELSTAKING166(uint256 amount) //inject NONSTANDARD NAMING public override WHENNOTPAUSED156 returns (bool) { // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } //stakingStorage.requireInStakingPeriod(); require(amount > 0, "Invalid amount."); _CANCELSTAKING147(msg.sender, amount); emit CANCELSTAKING945(msg.sender, amount); return true; } function GETTOTALREWARD238(uint256 blockNb, address _user) //inject NONSTANDARD NAMING public view returns (uint256 total) { if (blockNb > mEndBlock) { blockNb = mEndBlock; } // 1111111111 // 1,1111111cancel11 // 2,1111111 // 31111111 total = mOldReward[_user]; // include the old simple staking amount uint256 simpleStakingReward = 0; if (!syncUserInfo[msg.sender]) { (simpleStakingReward, ,) = mOldSimpleStaking.GETUSERINFO565(_user); } total = total.ADD955(simpleStakingReward); uint256 iMyOldStaking = 0; for ( uint256 i = 0; i < stakingStorage.GETSTAKESDATALENGTH308(_user); i++ ) { (uint256 stakingAmount, ) = stakingStorage.GETSTAKESDATABYINDEX845( _user, i ); iMyOldStaking = iMyOldStaking.ADD955(stakingAmount); } if (iMyOldStaking > 0) { uint256 oldStakingAmount = super.AMOUNTOF525(mOldStaking); uint256 iReward2 = super ._CALCREWARD319(blockNb, mOldStaking) .SUB444( mWidthdrawRewardFromOldStaking, "getTotalReward iReward2 sub overflow" ) .MUL509(iMyOldStaking) .DIV140(oldStakingAmount); total = total.ADD955(iReward2); } uint256 reward3 = super._CALCREWARD319(blockNb, _user); total = total.ADD955(reward3); } // claim reward // Note: 111111111token111 function CLAIM668() public override WHENNOTPAUSED156 returns (bool) { //inject NONSTANDARD NAMING //stakingStorage.requireStakingEnd() // require( // syncUserInfo[msg.sender], // "sync is required before perform action." // ); if (!syncUserInfo[msg.sender]) { SYNCUSERINFODATA21(msg.sender); } require( block.timestamp > claimRewardLockTime, "Not time to claim reward" ); uint256 iMyOldStaking = stakingStorage.STAKINGBALANCEOF960(msg.sender); uint256 iAmount = super.AMOUNTOF525(msg.sender); _CANCELSTAKING147(msg.sender, iMyOldStaking.ADD955(iAmount)); uint256 iReward = GETTOTALREWARD238(mEndBlock, msg.sender); _CLAIM850(msg.sender); mOldReward[msg.sender] = 0; linaToken.TRANSFER72(msg.sender, iReward); emit CLAIM827(msg.sender, iReward, iMyOldStaking.ADD955(iAmount)); return true; } function SETREWARDLOCKTIME580(uint256 newtime) public ONLYADMIN30 { //inject NONSTANDARD NAMING claimRewardLockTime = newtime; } function CALCREWARD808(uint256 curBlock, address _user) //inject NONSTANDARD NAMING public view returns (uint256) { return _CALCREWARDWITHVIEWSIMPLEAMOUNT431(curBlock, _user); } // This is copied particularly for catering the amount when user not sync function _CALCREWARDWITHVIEWSIMPLEAMOUNT431(uint256 curBlock, address _user) //inject NONSTANDARD NAMING internal view returns (uint256) { PoolInfo storage pool = mPoolInfo; UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.amount; if (curBlock > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = curBlock.SUB444( pool.lastRewardBlock, "cr curBlock sub overflow" ); uint256 curReward = multiplier.MUL509(rewardPerBlock); accRewardPerShare = accRewardPerShare.ADD955( curReward.MUL509(1e20).DIV140(lpSupply) ); } // Only logic added for old simpleStaking uint256 ssReward; uint256 ssAmount; uint256 ssRewardDebt; ( ssReward, ssAmount, ssRewardDebt ) = mOldSimpleStaking.GETUSERINFO565(_user); ssAmount = ssAmount.ADD955(user.amount); ssRewardDebt = ssRewardDebt.ADD955(user.rewardDebt); ssReward = ssReward.ADD955(user.reward); // uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub( uint256 newReward = ssAmount .MUL509(accRewardPerShare) .DIV140(1e20) .SUB444(ssRewardDebt, "cr newReward sub overflow"); return newReward.ADD955(ssReward); } function SETTRANSLOCK553(address target, uint256 locktime) public ONLYADMIN30 { //inject NONSTANDARD NAMING require( locktime >= now + 2 days, "locktime need larger than cur time 2 days" ); mTargetAddress = target; mTransLockTime = locktime; emit TRANSLOCK726(mTargetAddress, mTransLockTime); } function TRANSTOKENS575(uint256 amount) public ONLYADMIN30 { //inject NONSTANDARD NAMING require(mTransLockTime > 0, "mTransLockTime not set"); require(now > mTransLockTime, "Pls wait to unlock time"); linaToken.TRANSFER72(mTargetAddress, amount); } }
inject NONSTANDARD NAMING
function FUNCTIONCALLWITHVALUE757(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
12,739,002
./full_match/42/0xB132dDa09a9Ce074c2940C4e02fd03F809A755f7/sources/browser/Final_Implementation.sol
return the remaining funds of the deposit in case of error of normal code
function returndeposit() public payable { msg.sender.transfer(balances[msg.sender]); }
16,265,528
./full_match/80001/0xafB8D3F0d92461d3c860E4F7FA1B28a5BF8a1cF8/sources/MintingNFT.sol
Mint NFT of [category] /
function mint(uint256 category) public payable{ require(alreadyMinted[msg.sender] == 0, "Minted already."); if(category == 1) require(currentCounts[category] + 1 <= 50, "Can not exceed Max Count"); else if(category == 2) require(currentCounts[category] + 1 <= 50, "Can not exceed Max Count"); else if(category == 3) require(currentCounts[category] + 1 <= 50, "Can not exceed Max Count"); require(msg.value >= prices[category], "Insufficient Payment"); uint256 totalsupply = totalSupply(); _mint(msg.sender, totalsupply + 1); currentCounts[category]++; alreadyMinted[msg.sender] = 1; vtr_address.push(msg.sender); vtr_category.push(category); creator.transfer(msg.value); }
874,110
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* Contract Imports */ import { L1ToL2TransactionQueue } from "../queue/L1ToL2TransactionQueue.sol"; import { SafetyTransactionQueue } from "../queue/SafetyTransactionQueue.sol"; /* Library Imports */ import { ContractResolver } from "../utils/resolvers/ContractResolver.sol"; import { DataTypes } from "../utils/libraries/DataTypes.sol"; import { RollupMerkleUtils } from "../utils/libraries/RollupMerkleUtils.sol"; /** * @title CanonicalTransactionChain */ contract CanonicalTransactionChain is ContractResolver { /* * Events */ event L1ToL2BatchAppended( bytes32 _batchHeaderHash); event SafetyQueueBatchAppended( bytes32 _batchHeaderHash); event SequencerBatchAppended(bytes32 _batchHeaderHash); /* * Contract Variables */ address public sequencer; uint public forceInclusionPeriodSeconds; uint public cumulativeNumElements; bytes32[] public batches; uint public lastOVMTimestamp; /* * Constructor */ /** * @param _addressResolver Address of the AddressResolver contract. * @param _sequencer Address of the sequencer. * @param _forceInclusionPeriodSeconds Timeout in seconds when a transaction must be published. */ constructor( address _addressResolver, address _sequencer, uint _forceInclusionPeriodSeconds ) public ContractResolver(_addressResolver) { sequencer = _sequencer; forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds; lastOVMTimestamp = 0; } /* * Public Functions */ /** * @return Total number of published transaction batches. */ function getBatchesLength() public view returns (uint) { return batches.length; } /** * Computes the hash of a batch header. * @param _batchHeader Header to hash. * @return Hash of the provided header. */ function hashBatchHeader( DataTypes.TxChainBatchHeader memory _batchHeader ) public pure returns (bytes32) { return keccak256(abi.encodePacked( _batchHeader.timestamp, _batchHeader.isL1ToL2Tx, _batchHeader.elementsMerkleRoot, _batchHeader.numElementsInBatch, _batchHeader.cumulativePrevElements )); } /** * Checks whether a sender is allowed to append to the chain. * @param _sender Address to check. * @return Whether or not the address can append. */ function authenticateAppend( address _sender ) public view returns (bool) { return _sender == sequencer; } /** * Attempts to append a transaction batch from pending L1 transactions. */ function appendL1ToL2Batch() public { L1ToL2TransactionQueue l1ToL2Queue = resolveL1ToL2TransactionQueue(); SafetyTransactionQueue safetyQueue = resolveSafetyTransactionQueue(); DataTypes.TimestampedHash memory l1ToL2Header = l1ToL2Queue.peek(); require( safetyQueue.isEmpty() || l1ToL2Header.timestamp <= safetyQueue.peekTimestamp(), "Must process older SafetyQueue batches first to enforce timestamp monotonicity" ); _appendQueueBatch(l1ToL2Header, true); l1ToL2Queue.dequeue(); } /** * Attempts to append a transaction batch from the safety queue. */ function appendSafetyBatch() public { L1ToL2TransactionQueue l1ToL2Queue = resolveL1ToL2TransactionQueue(); SafetyTransactionQueue safetyQueue = resolveSafetyTransactionQueue(); DataTypes.TimestampedHash memory safetyHeader = safetyQueue.peek(); require( l1ToL2Queue.isEmpty() || safetyHeader.timestamp <= l1ToL2Queue.peekTimestamp(), "Must process older L1ToL2Queue batches first to enforce timestamp monotonicity" ); _appendQueueBatch(safetyHeader, false); safetyQueue.dequeue(); } /** * Attempts to append a batch provided by the sequencer. * @param _txBatch Transaction batch to append. * @param _timestamp Timestamp for the batch. */ function appendSequencerBatch( bytes[] memory _txBatch, uint _timestamp ) public { L1ToL2TransactionQueue l1ToL2Queue = resolveL1ToL2TransactionQueue(); SafetyTransactionQueue safetyQueue = resolveSafetyTransactionQueue(); require( authenticateAppend(msg.sender), "Message sender does not have permission to append a batch" ); require( _txBatch.length > 0, "Cannot submit an empty batch" ); require( _timestamp + forceInclusionPeriodSeconds > now, "Cannot submit a batch with a timestamp older than the sequencer inclusion period" ); require( _timestamp <= now, "Cannot submit a batch with a timestamp in the future" ); require( l1ToL2Queue.isEmpty() || _timestamp <= l1ToL2Queue.peekTimestamp(), "Must process older L1ToL2Queue batches first to enforce timestamp monotonicity" ); require( safetyQueue.isEmpty() || _timestamp <= safetyQueue.peekTimestamp(), "Must process older SafetyQueue batches first to enforce timestamp monotonicity" ); require( _timestamp >= lastOVMTimestamp, "Timestamps must monotonically increase" ); lastOVMTimestamp = _timestamp; RollupMerkleUtils merkleUtils = resolveRollupMerkleUtils(); bytes32 batchHeaderHash = keccak256(abi.encodePacked( _timestamp, false, // isL1ToL2Tx merkleUtils.getMerkleRoot(_txBatch), // elementsMerkleRoot _txBatch.length, // numElementsInBatch cumulativeNumElements // cumulativeNumElements )); batches.push(batchHeaderHash); cumulativeNumElements += _txBatch.length; emit SequencerBatchAppended(batchHeaderHash); } /** * Checks that an element is included within a published batch. * @param _element Element to prove within the batch. * @param _position Index of the element within the batch. * @param _inclusionProof Inclusion proof for the element/batch. */ function verifyElement( bytes memory _element, uint _position, DataTypes.TxElementInclusionProof memory _inclusionProof ) public view returns (bool) { // For convenience, store the batchHeader DataTypes.TxChainBatchHeader memory batchHeader = _inclusionProof.batchHeader; // make sure absolute position equivalent to relative positions if (_position != _inclusionProof.indexInBatch + batchHeader.cumulativePrevElements) { return false; } // verify elementsMerkleRoot RollupMerkleUtils merkleUtils = resolveRollupMerkleUtils(); if (!merkleUtils.verify( batchHeader.elementsMerkleRoot, _element, _inclusionProof.indexInBatch, _inclusionProof.siblings )) { return false; } //compare computed batch header with the batch header in the list. return hashBatchHeader(batchHeader) == batches[_inclusionProof.batchIndex]; } /* * Internal Functions */ /** * Appends a batch. * @param _timestampedHash Timestamped transaction hash. * @param _isL1ToL2Tx Whether or not this is an L1-L2 transaction. */ function _appendQueueBatch( DataTypes.TimestampedHash memory _timestampedHash, bool _isL1ToL2Tx ) internal { uint timestamp = _timestampedHash.timestamp; require( timestamp + forceInclusionPeriodSeconds <= now || authenticateAppend(msg.sender), "Message sender does not have permission to append this batch" ); lastOVMTimestamp = timestamp; bytes32 elementsMerkleRoot = _timestampedHash.txHash; uint numElementsInBatch = 1; bytes32 batchHeaderHash = keccak256(abi.encodePacked( timestamp, _isL1ToL2Tx, elementsMerkleRoot, numElementsInBatch, cumulativeNumElements // cumulativePrevElements )); batches.push(batchHeaderHash); cumulativeNumElements += numElementsInBatch; if (_isL1ToL2Tx) { emit L1ToL2BatchAppended(batchHeaderHash); } else { emit SafetyQueueBatchAppended(batchHeaderHash); } } /* * Contract Resolution */ function resolveL1ToL2TransactionQueue() internal view returns (L1ToL2TransactionQueue) { return L1ToL2TransactionQueue(resolveContract("L1ToL2TransactionQueue")); } function resolveSafetyTransactionQueue() internal view returns (SafetyTransactionQueue) { return SafetyTransactionQueue(resolveContract("SafetyTransactionQueue")); } function resolveRollupMerkleUtils() internal view returns (RollupMerkleUtils) { return RollupMerkleUtils(resolveContract("RollupMerkleUtils")); } }
Appends a batch. _timestampedHash Timestamped transaction hash. _isL1ToL2Tx Whether or not this is an L1-L2 transaction./
function _appendQueueBatch( DataTypes.TimestampedHash memory _timestampedHash, bool _isL1ToL2Tx ) internal { uint timestamp = _timestampedHash.timestamp; require( timestamp + forceInclusionPeriodSeconds <= now || authenticateAppend(msg.sender), "Message sender does not have permission to append this batch" ); lastOVMTimestamp = timestamp; bytes32 elementsMerkleRoot = _timestampedHash.txHash; uint numElementsInBatch = 1; bytes32 batchHeaderHash = keccak256(abi.encodePacked( timestamp, _isL1ToL2Tx, elementsMerkleRoot, numElementsInBatch, )); batches.push(batchHeaderHash); cumulativeNumElements += numElementsInBatch; if (_isL1ToL2Tx) { emit L1ToL2BatchAppended(batchHeaderHash); emit SafetyQueueBatchAppended(batchHeaderHash); } }
2,539,636
/** * SPDX-License-Identifier: MIT * * Copyright (c) 2018-2022 CENTRE SECZ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.8.0; import "./IVerificationRegistry.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "hardhat/console.sol"; /** * @title A persistent IVerificationRegistry implementation. */ contract VerificationRegistry is Ownable, EIP712("VerificationRegistry", "1.0"), IVerificationRegistry { // Verifier addresses mapped to metadata (VerifierInfo) about the Verifiers. mapping(address => VerifierInfo) private _verifiers; // Verifier signing keys mapped to verifier addresses mapping(address => address) private _signers; // Total number of active registered verifiers uint256 _verifierCount; // All verification records keyed by their uuids mapping(bytes32 => VerificationRecord) private _verifications; // Verifications mapped to subject addresses (those who receive verifications) mapping(address => bytes32[]) private _verificationsForSubject; // Verfications issued by a given trusted verifier (those who execute verifications) mapping(address => bytes32[]) private _verificationsForVerifier; // Total verifications registered (mapping keys not being enumerable, countable, etc) uint256 private _verificationRecordCount; /*****************************/ /* VERIFIER MANAGEMENT LOGIC */ /*****************************/ /** * @inheritdoc IVerificationRegistry */ function addVerifier(address verifierAddress, VerifierInfo memory verifierInfo) external override onlyOwner { require(_verifiers[verifierAddress].name == 0, "VerificationRegistry: Verifier Address Exists"); _verifiers[verifierAddress] = verifierInfo; _signers[verifierInfo.signer] = verifierAddress; _verifierCount++; emit VerifierAdded(verifierAddress, verifierInfo); } /** * @inheritdoc IVerificationRegistry */ function isVerifier(address account) external override view returns (bool) { return _verifiers[account].name != 0; } /** * @inheritdoc IVerificationRegistry */ function getVerifierCount() external override view returns(uint) { return _verifierCount; } /** * @inheritdoc IVerificationRegistry */ function getVerifier(address verifierAddress) external override view returns (VerifierInfo memory) { require(_verifiers[verifierAddress].name != 0, "VerificationRegistry: Unknown Verifier Address"); return _verifiers[verifierAddress]; } /** * @inheritdoc IVerificationRegistry */ function updateVerifier(address verifierAddress, VerifierInfo memory verifierInfo) external override onlyOwner { require(_verifiers[verifierAddress].name != 0, "VerificationRegistry: Unknown Verifier Address"); _verifiers[verifierAddress] = verifierInfo; _signers[verifierInfo.signer] = verifierAddress; emit VerifierUpdated(verifierAddress, verifierInfo); } /** * @inheritdoc IVerificationRegistry */ function removeVerifier(address verifierAddress) external override onlyOwner { require(_verifiers[verifierAddress].name != 0, "VerificationRegistry: Verifier Address Does Not Exist"); delete _signers[_verifiers[verifierAddress].signer]; delete _verifiers[verifierAddress]; _verifierCount--; emit VerifierRemoved(verifierAddress); } /**********************/ /* VERIFICATION LOGIC */ /**********************/ modifier onlyVerifier() { require( _verifiers[msg.sender].name != 0, "VerificationRegistry: Caller is not a Verifier" ); _; } /** * @inheritdoc IVerificationRegistry */ function getVerificationCount() external override view returns(uint256) { return _verificationRecordCount; } /** * @inheritdoc IVerificationRegistry */ function isVerified(address subject) external override view returns (bool) { require(subject != address(0), "VerificationRegistry: Invalid address"); bytes32[] memory subjectRecords = _verificationsForSubject[subject]; for (uint i=0; i<subjectRecords.length; i++) { VerificationRecord memory record = _verifications[subjectRecords[i]]; if (!record.revoked && record.expirationTime > block.timestamp) { return true; } } return false; } /** * @inheritdoc IVerificationRegistry */ function getVerification(bytes32 uuid) external override view returns (VerificationRecord memory) { return _verifications[uuid]; } /** * @inheritdoc IVerificationRegistry */ function getVerificationsForSubject(address subject) external override view returns (VerificationRecord[] memory) { require(subject != address(0), "VerificationRegistry: Invalid address"); bytes32[] memory subjectRecords = _verificationsForSubject[subject]; VerificationRecord[] memory records = new VerificationRecord[](subjectRecords.length); for (uint i=0; i<subjectRecords.length; i++) { VerificationRecord memory record = _verifications[subjectRecords[i]]; records[i] = record; } return records; } /** * @inheritdoc IVerificationRegistry */ function getVerificationsForVerifier(address verifier) external override view returns (VerificationRecord[] memory) { require(verifier != address(0), "VerificationRegistry: Invalid address"); bytes32[] memory verifierRecords = _verificationsForVerifier[verifier]; VerificationRecord[] memory records = new VerificationRecord[](verifierRecords.length); for (uint i=0; i<verifierRecords.length; i++) { VerificationRecord memory record = _verifications[verifierRecords[i]]; records[i] = record; } return records; } /** * @inheritdoc IVerificationRegistry */ function revokeVerification(bytes32 uuid) external override onlyVerifier { require(_verifications[uuid].verifier == msg.sender, "VerificationRegistry: Caller is not the original verifier"); _verifications[uuid].revoked = true; emit VerificationRevoked(uuid); } /** * @inheritdoc IVerificationRegistry */ function removeVerification(bytes32 uuid) external override onlyVerifier { require(_verifications[uuid].verifier == msg.sender, "VerificationRegistry: Caller is not the verifier of the referenced record"); delete _verifications[uuid]; emit VerificationRemoved(uuid); } /** * @inheritdoc IVerificationRegistry */ function registerVerification( VerificationResult memory verificationResult, bytes memory signature ) external override onlyVerifier returns (VerificationRecord memory) { _beforeVerificationValidation(verificationResult); VerificationRecord memory verificationRecord = _validateVerificationResult(verificationResult, signature); require( verificationRecord.verifier == msg.sender, "VerificationRegistry: Caller is not the verifier of the verification" ); _persistVerificationRecord(verificationRecord); emit VerificationResultConfirmed(verificationRecord); return verificationRecord; } /** * A caller may be the subject of a successful VerificationResult * and register that verification itself rather than rely on a verifier * to do so. The registry will validate the result, and if the result * is valid, signed by a known verifier, and the subject of the verification * is this caller, then the resulting VerificationRecord will be persisted and returned. * * To use this pattern, a derived contract should inherit and invoke this function, * otherwise the caller will not be the subject but an intermediary. * See ThresholdToken.sol for a simple example. */ function _registerVerificationBySubject( VerificationResult memory verificationResult, bytes memory signature ) internal returns (VerificationRecord memory) { require( verificationResult.subject == msg.sender, "VerificationRegistry: Caller is not the verified subject" ); _beforeVerificationValidation(verificationResult); VerificationRecord memory verificationRecord = _validateVerificationResult(verificationResult, signature); _persistVerificationRecord(verificationRecord); emit VerificationResultConfirmed(verificationRecord); return verificationRecord; } /** * A subject can remove records about itself, similarly to how a verifier can * remove records about a subject. Nothing is truly 'deleted' from on-chain storage, * as the record exists in previous state, but this does prevent the record from * usage in the future. * * To use this pattern, a derived contract should inherit and invoke this function, * otherwise the caller will not be the subject but an intermediary. * See ThresholdToken.sol for a simple example. */ function _removeVerificationBySubject(bytes32 uuid) internal { require(_verifications[uuid].subject == msg.sender, "VerificationRegistry: Caller is not the subject of the referenced record"); delete _verifications[uuid]; emit VerificationRemoved(uuid); } /***********************************/ /* VERIFICATION INTERNAL MECHANICS */ /***********************************/ /** * This hook may be overridden to enable registry-specific or credential-specific * filtering of a Verification Result. For example, a registry devoted to risk scoring * or accredited investor status may make assertions based on the result's payload * or on the designation of the issuer or verifier. The default behavior is a no-op, * no additional processing of the payload or other properties is executed. */ function _beforeVerificationValidation(VerificationResult memory verificationResult) internal { } /** * A verifier provides a signed hash of a verification result it * has created for a subject address. This function recreates the hash * given the result artifacts and then uses it and the signature to recover * the public address of the signer. If that address is a trusted verifier's * signing address, and the assessment completes within the deadline (unix time in * seconds since epoch), then the verification succeeds and is valid until revocation, * expiration, or removal from storage. */ function _validateVerificationResult( VerificationResult memory verificationResult, bytes memory signature ) internal view returns(VerificationRecord memory) { bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( keccak256("VerificationResult(string schema,address subject,uint256 expiration)"), keccak256(bytes(verificationResult.schema)), verificationResult.subject, verificationResult.expiration ))); // recover the public address corresponding to the signature and regenerated hash address signerAddress = ECDSA.recover(digest, signature); // retrieve a verifier address for the recovered address address verifierAddress = _signers[signerAddress]; // ensure the verifier is registered and its signer is the recovered address require( _verifiers[verifierAddress].signer == signerAddress, "VerificationRegistry: Signed digest cannot be verified" ); // ensure that the result has not expired require( verificationResult.expiration > block.timestamp, "VerificationRegistry: Verification confirmation expired" ); // create a VerificationRecord VerificationRecord memory verificationRecord = VerificationRecord({ uuid: 0, verifier: verifierAddress, subject: verificationResult.subject, entryTime: block.timestamp, expirationTime: verificationResult.expiration, revoked: false }); // generate a UUID for the record bytes32 uuid = _createVerificationRecordUUID(verificationRecord); verificationRecord.uuid = uuid; return verificationRecord; } /** * After validating a Verification Result and generating a Verification Record, * the registry increments the record count, adds the record to a map based on its uuid, * and associates the record's uuid with the verifier's and subject's existing record mappings. */ function _persistVerificationRecord(VerificationRecord memory verificationRecord) internal { // persist the record count and the record itself, and map the record to verifier and subject _verificationRecordCount++; _verifications[verificationRecord.uuid] = verificationRecord; _verificationsForSubject[verificationRecord.subject].push(verificationRecord.uuid); _verificationsForVerifier[verificationRecord.verifier].push(verificationRecord.uuid); } /** * Generate a UUID for a VerificationRecord. */ function _createVerificationRecordUUID(VerificationRecord memory verificationRecord) private view returns (bytes32) { return keccak256( abi.encodePacked( verificationRecord.verifier, verificationRecord.subject, verificationRecord.entryTime, verificationRecord.expirationTime, _verificationRecordCount ) ); } }
/ VERIFIER MANAGEMENT LOGIC // @inheritdoc IVerificationRegistry/
function addVerifier(address verifierAddress, VerifierInfo memory verifierInfo) external override onlyOwner { require(_verifiers[verifierAddress].name == 0, "VerificationRegistry: Verifier Address Exists"); _verifiers[verifierAddress] = verifierInfo; _signers[verifierInfo.signer] = verifierAddress; _verifierCount++; emit VerifierAdded(verifierAddress, verifierInfo); }
13,113,918
library AVMMemoryContext32 { struct Context { uint256[] readAccesses; uint256[] writeAccesses; uint writeIdx; uint cachedRead; uint cachedReadValue; uint windowOffset; uint windowLength; bool valid; bool fault; } event trace(string); event traceNum(uint); event MissingRead(uint); event BadWriteAddress(uint, uint); event BadWriteValue(uint, uint, uint); function initContext(uint offset, uint window, uint256[] memory readAccesses, uint256[] memory writeAccesses) internal returns (Context memory) { Context memory ctx; ctx.readAccesses = readAccesses; ctx.writeAccesses = writeAccesses; ctx.writeIdx = 0; ctx.windowOffset = offset; ctx.windowLength = window; ctx.cachedRead = (uint) (-1); ctx.cachedReadValue = 0; ctx.valid = true; ctx.fault = false; return ctx; } function read256(Context ctx, uint addr) internal returns (uint) { if (!ctx.valid) return 0; uint v; if (addr / 32 >= ctx.windowLength / 32) { ctx.fault = true; return 0; } else { addr = addr + ctx.windowOffset; } for (uint i = 0; i < ctx.readAccesses.length; i += 2) { if (ctx.readAccesses[i] == (addr / 32)) { return ctx.readAccesses[i+1]; } } ctx.valid = false; MissingRead(addr / 32); return 0; } function read32(Context ctx, uint addr) internal returns (uint32) { uint v = read256(ctx, addr); // Shift down to chosen word for (uint j = ((addr / 4) % 8); j < 7; j++) { v = v / 4294967296; } return (uint32) (v); } function readByte(Context ctx, uint addr) internal returns (uint8) { uint32 v = read32(ctx, addr); for (uint j = (addr % 4); j < 3; j++) { v = v / 256; } return (uint8) (v); } function write256(Context ctx, uint addr, uint value) internal { if (!ctx.valid) return; if (addr / 32 >= ctx.windowLength / 32) { ctx.fault = true; return; } else { addr = addr + ctx.windowOffset; } trace("Write"); if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) { // Insufficient writes trace("Insufficient Writes"); ctx.valid = false; return; } trace("Reading write address"); if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) { // Wrong write address BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]); ctx.valid = false; return; } // Whole overwrite - ignore prior value ctx.writeIdx++; trace("Reading write value"); if (ctx.writeAccesses[ctx.writeIdx++] != value) { // Wrong write value BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]); ctx.valid = false; return; } trace("Updating read values for write"); for (uint i = 0; i < ctx.readAccesses.length; i += 2) { if (ctx.readAccesses[i] == addr / 32) { ctx.readAccesses[i+1] = value; } } } function write32(Context ctx, uint addr, uint value) internal { if (!ctx.valid) return; if (addr / 32 >= ctx.windowLength / 32) { ctx.fault = true; return; } else { addr = addr + ctx.windowOffset; } trace("Write"); if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) { // Insufficient writes trace("Insufficient Writes"); ctx.valid = false; return; } trace("Reading write address"); if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) { // Wrong write address BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]); ctx.valid = false; return; } trace("Reading write prior value"); uint result = ctx.writeAccesses[ctx.writeIdx++]; uint mask = 4294967295; value = value & mask; // Shift up to chosen word for (uint j = ((addr / 4) % 8); j < 7; j++) { mask = mask * 4294967296; value = value * 4294967296; } result = (result & (~mask)) | value; trace("Reading write value"); if (ctx.writeAccesses[ctx.writeIdx++] != result) { // Wrong write value BadWriteValue(addr / 32, result, ctx.writeAccesses[ctx.writeIdx - 1]); ctx.valid = false; return; } trace("Updating future read values from write"); for (uint i = 0; i < ctx.readAccesses.length; i += 2) { if (ctx.readAccesses[i] == addr / 32) { ctx.readAccesses[i+1] = value; } } } function isValid(Context memory ctx) internal returns (bool) { if (ctx.writeAccesses.length != ctx.writeIdx) { // Excess reads ctx.valid = false; } return ctx.valid; } }
Insufficient writes Wrong write address Wrong write value
function write256(Context ctx, uint addr, uint value) internal { if (!ctx.valid) return; if (addr / 32 >= ctx.windowLength / 32) { ctx.fault = true; return; addr = addr + ctx.windowOffset; } trace("Write"); if (ctx.writeAccesses.length < (ctx.writeIdx + 2)) { trace("Insufficient Writes"); ctx.valid = false; return; } trace("Reading write address"); if (ctx.writeAccesses[ctx.writeIdx++] != (addr / 32)) { BadWriteAddress(addr / 32, ctx.writeAccesses[ctx.writeIdx-1]); ctx.valid = false; return; } trace("Reading write value"); if (ctx.writeAccesses[ctx.writeIdx++] != value) { BadWriteValue(addr / 32, value, ctx.writeAccesses[ctx.writeIdx - 1]); ctx.valid = false; return; } trace("Updating read values for write"); for (uint i = 0; i < ctx.readAccesses.length; i += 2) { if (ctx.readAccesses[i] == addr / 32) { ctx.readAccesses[i+1] = value; } } }
13,056,692
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.0; import "../utils/Ownable.sol"; import "../utils/LibBytes.sol"; import "../utils/LibRichErrors.sol"; import "../exchange-libs/LibExchangeRichErrors.sol"; import "./interfaces/IAssetProxy.sol"; import "./interfaces/IAssetProxyDispatcher.sol"; abstract contract MixinAssetProxyDispatcher is Ownable, IAssetProxyDispatcher { using LibBytes for bytes; // Mapping from Asset Proxy Id's to their respective Asset Proxy mapping (bytes4 => address) internal _assetProxies; /// @dev Registers an asset proxy to its asset proxy id. /// Once an asset proxy is registered, it cannot be unregistered. /// @param assetProxy Address of new asset proxy to register. function registerAssetProxy(address assetProxy) override external onlyOwner { // Ensure that no asset proxy exists with current id. bytes4 assetProxyId = IAssetProxy(assetProxy).getProxyId(); address currentAssetProxy = _assetProxies[assetProxyId]; if (currentAssetProxy != address(0)) { LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyExistsError( assetProxyId, currentAssetProxy )); } // Add asset proxy and log registration. _assetProxies[assetProxyId] = assetProxy; emit AssetProxyRegistered( assetProxyId, assetProxy ); } /// @dev Gets an asset proxy. /// @param assetProxyId Id of the asset proxy. /// @return assetProxy The asset proxy address registered to assetProxyId. Returns 0x0 if no proxy is registered. function getAssetProxy(bytes4 assetProxyId) override external view returns (address assetProxy) { return _assetProxies[assetProxyId]; } /// @dev Forwards arguments to assetProxy and calls `transferFrom`. Either succeeds or throws. /// @param orderHash Hash of the order associated with this transfer. /// @param assetData Byte array encoded for the asset. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param amount Amount of token to transfer. function _dispatchTransferFrom( bytes32 orderHash, bytes memory assetData, address from, address to, uint256 amount ) internal { // Do nothing if no amount should be transferred. if (amount > 0) { // Ensure assetData is padded to 32 bytes (excluding the id) and is at least 4 bytes long if (assetData.length % 32 != 4) { LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError( LibExchangeRichErrors.AssetProxyDispatchErrorCodes.INVALID_ASSET_DATA_LENGTH, orderHash, assetData )); } // Lookup assetProxy. bytes4 assetProxyId = assetData.readBytes4(0); address assetProxy = _assetProxies[assetProxyId]; // Ensure that assetProxy exists if (assetProxy == address(0)) { LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyDispatchError( LibExchangeRichErrors.AssetProxyDispatchErrorCodes.UNKNOWN_ASSET_PROXY, orderHash, assetData )); } // Construct the calldata for the transferFrom call. bytes memory proxyCalldata = abi.encodeWithSelector( IAssetProxy(address(0)).transferFrom.selector, assetData, from, to, amount ); // Call the asset proxy's transferFrom function with the constructed calldata. (bool didSucceed, bytes memory returnData) = assetProxy.call(proxyCalldata); // If the transaction did not succeed, revert with the returned data. if (!didSucceed) { LibRichErrors.rrevert(LibExchangeRichErrors.AssetProxyTransferError( orderHash, assetData, returnData )); } } } }
Gets an asset proxy. assetProxyId Id of the asset proxy. return assetProxy The asset proxy address registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId) override external view returns (address assetProxy) { return _assetProxies[assetProxyId]; }
12,547,482
pragma solidity ^0.6.12; contract EIP712Base { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeparator; constructor(string memory name) public { _setDomainSeparator(name); } function _setDomainSeparator(string memory name) internal { domainSeparator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeparator() public view returns (bytes32) { return domainSeparator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeparator(), messageHash) ); } } import "@openzeppelin/contracts/math/SafeMath.sol"; import "./EIP712Base.sol"; pragma solidity ^0.6.12; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } constructor(string memory name) public EIP712Base(name) {} function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } function _msgSender() internal view virtual returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } pragma solidity 0.6.12; interface ISelfServiceAccessControls { function isEnabledForAccount(address account) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/ISelfServiceAccessControls.sol"; import "../../forwarder/NativeMetaTransaction.sol"; contract SelfServiceAccessControls is Ownable, ISelfServiceAccessControls, NativeMetaTransaction("SelfServiceAccessControls") { function _msgSender() internal view override(Context, NativeMetaTransaction) returns (address payable sender) { return NativeMetaTransaction._msgSender(); } // Simple map to only allow certain artist create editions at first mapping(address => bool) public allowedArtists; // When true any existing NR artist can mint their own editions bool public openToAllArtist = false; /** * @dev Controls is the contract is open to all * @dev Only callable from owner */ function setOpenToAllArtist(bool _openToAllArtist) onlyOwner public { openToAllArtist = _openToAllArtist; } /** * @dev Controls who can call this contract * @dev Only callable from owner */ function setAllowedArtist(address _artist, bool _allowed) onlyOwner public { allowedArtists[_artist] = _allowed; } /** * @dev Checks to see if the account can create editions */ function isEnabledForAccount(address account) public override view returns (bool) { if (openToAllArtist) { return true; } return allowedArtists[account]; } /** * @dev Allows for the ability to extract stuck ether * @dev Only callable from owner */ function withdrawStuckEther(address _withdrawalAccount) onlyOwner public { require(_withdrawalAccount != address(0), "Invalid address provided"); payable(_withdrawalAccount).transfer(address(this).balance); } } // 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; /** * @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 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; } }
Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
function _msgSender() internal view virtual returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } sender = msg.sender; } return sender; }
6,877,261
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Fundraiser donations /// @author kwight /// @notice This contract allows register charities to receive donations for campaigns. contract Fundraisers is Ownable { mapping(address => Charity) private charityRegistry; address[] private charities; Program[] private programs; Donation[] private donations; enum ProgramStatus { Active, Cancelled, Complete } struct Charity { string name; uint256 index; } struct Program { string title; ProgramStatus status; address charity; } struct Donation { address doner; uint256 programId; uint256 amount; } /// @notice Emit an event when a charity is registered. /// @param charityAddress Address of the registered charity. /// @param name Name of the charity. event CharityRegistered(address charityAddress, string name); /// @notice Emit an event when a charity is removed by the owner. /// @param charityAddress Address of the removed charity. event CharityRemoved(address charityAddress); /// @notice Emit an event when a charity registers a program. /// @param programId Index in the programs array. /// @param charityAddress Address of the charity doing the registering. event ProgramRegistered(uint256 programId, address charityAddress); /// @notice Emit an event when a charity cancels a program. /// @param programId Index in the programs array. /// @param charityAddress Address of the charity doing the cancelling. event ProgramCancelled(uint256 programId, address charityAddress); /// @notice Emit an event when a charity marks a program as completed. /// @param programId Index in the programs array. /// @param charityAddress Address of the charity marking the completion. event ProgramCompleted(uint256 programId, address charityAddress); /// @notice Emit an event when a donation is received. /// @param amount Amount of the donation (in wei). /// @param charityAddress Address of the charity receiving the funds. /// @param programId Index in the programs array. /// @param doner Address of the doner. event DonationReceived( uint256 amount, address charityAddress, uint256 programId, address doner ); modifier isOwnerOrCharity(address charityAddress) { require( msg.sender == owner() || msg.sender == charityAddress, "unauthorized" ); _; } modifier onlyCharity() { require(isRegisteredCharity(msg.sender) == true, "unauthorized"); _; } /// @notice Verify a given address is a registered charity. /// @param charityAddress Address being verified. /// @return True if registered, false otherwise. function isRegisteredCharity(address charityAddress) public view returns (bool) { if (charities.length == 0) return false; return (charities[charityRegistry[charityAddress].index] == charityAddress); } /// @notice Register a charity. /// @param charityAddress Address of the charity to be registered. /// @param name Name of the charity. function registerCharity(address charityAddress, string memory name) public onlyOwner { require( isRegisteredCharity(charityAddress) == false, "charity already exists" ); charities.push(charityAddress); charityRegistry[charityAddress].name = name; charityRegistry[charityAddress].index = charities.length - 1; emit CharityRegistered(charityAddress, name); } /// @notice Remove a charity. /// @param charityAddress Address of the charity to be removed. function removeCharity(address charityAddress) public isOwnerOrCharity(charityAddress) { require( isRegisteredCharity(charityAddress) == true, "charity does not exist" ); uint256 toRemove = charityRegistry[charityAddress].index; address toMove = charities[charities.length - 1]; charityRegistry[toMove].index = toRemove; charities[toRemove] = toMove; charities.pop(); emit CharityRemoved(charityAddress); } /// @notice Get stored data for the given charity. /// @param charityAddress Address of the charity requested. /// @return Charity struct instance. function getCharity(address charityAddress) public view returns (Charity memory) { require( isRegisteredCharity(charityAddress) == true, "charity does not exist" ); return charityRegistry[charityAddress]; } /// @notice Get data for all registered charities. /// @return Array of Charity struct instances. function getCharities() public view returns (address[] memory) { return charities; } /// @notice Get data for all registered programs. /// @return Array of Program struct instances. function getPrograms() public view returns (Program[] memory) { return programs; } /// @notice Register a program. /// @param title The name of the program. function registerProgram(string memory title) public onlyCharity { programs.push( Program({ title: title, status: ProgramStatus.Active, charity: msg.sender }) ); emit ProgramRegistered(programs.length - 1, msg.sender); } /// @notice Cancel an active program. /// @param programId Index of the program to be cancelled. function cancelProgram(uint256 programId) public onlyCharity { require(programs.length > programId, "program does not exist"); require(programs[programId].charity == msg.sender, "unauthorized"); require( programs[programId].status == ProgramStatus.Active, "program is not active" ); programs[programId].status = ProgramStatus.Cancelled; emit ProgramCancelled(programId, msg.sender); } /// @notice Mark an active program as complete. /// @param programId Index of the program to be marked complete. function completeProgram(uint256 programId) public onlyCharity { require(programs.length > programId, "program does not exist"); require(programs[programId].charity == msg.sender, "unauthorized"); require( programs[programId].status == ProgramStatus.Active, "program is not active" ); programs[programId].status = ProgramStatus.Complete; emit ProgramCompleted(programId, msg.sender); } /// @notice Donate ether to a charity's program. /// @param programId Index of the program "receiving" the donation. function donate(uint256 programId) public payable { require(programs.length > programId, "program does not exist"); require( programs[programId].status == ProgramStatus.Active, "program is not active" ); Program memory receivingProgram = programs[programId]; donations.push( Donation({ doner: msg.sender, programId: programId, amount: msg.value }) ); (bool sent, ) = receivingProgram.charity.call{value: msg.value}(""); require(sent, "ether not sent to charity"); emit DonationReceived( msg.value, receivingProgram.charity, programId, msg.sender ); } /// @notice Get data for all donations. /// @return Array of Donation struct instances. function getDonations() public view returns (Donation[] memory) { return donations; } }
Register a charity. charityAddress Address of the charity to be registered. name Name of the charity.
function registerCharity(address charityAddress, string memory name) public onlyOwner { require( isRegisteredCharity(charityAddress) == false, "charity already exists" ); charities.push(charityAddress); charityRegistry[charityAddress].name = name; charityRegistry[charityAddress].index = charities.length - 1; emit CharityRegistered(charityAddress, name); }
7,269,337
pragma solidity ^0.5.16; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./WETHInterface.sol"; import "./MoneyMarketInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract CDP { using SafeMath for uint256; uint256 constant expScale = 10**18; uint256 constant collateralRatioBuffer = 25 * 10**16; address creator; address payable owner; WETHInterface weth; MoneyMarketInterface compoundMoneyMarket; IERC20 borrowedToken; event Log(uint256 x, string m); event Log(int256 x, string m); constructor( address payable _owner, address tokenAddress, address wethAddress, address moneyMarketAddress ) public { creator = msg.sender; owner = _owner; borrowedToken = IERC20(tokenAddress); compoundMoneyMarket = MoneyMarketInterface(moneyMarketAddress); weth = WETHInterface(wethAddress); weth.approve(moneyMarketAddress, uint256(-1)); borrowedToken.approve(address(compoundMoneyMarket), uint256(-1)); } /* @dev called from borrow factory, wraps eth and supplies weth, then borrows the token at address supplied in constructor */ function fund() external payable { require(creator == msg.sender); weth.deposit.value(msg.value)(); uint256 supplyStatus = compoundMoneyMarket.supply( address(weth), msg.value ); require(supplyStatus == 0, "supply failed"); /* --------- borrow the tokens ----------- */ uint256 collateralRatio = compoundMoneyMarket.collateralRatio(); (uint256 status, uint256 totalSupply, uint256 totalBorrow) = compoundMoneyMarket .calculateAccountValues(address(this)); require(status == 0, "calculating account values failed"); uint256 availableBorrow = findAvailableBorrow( totalSupply, totalBorrow, collateralRatio ); uint256 assetPrice = compoundMoneyMarket.assetPrices( address(borrowedToken) ); /* available borrow & asset price are both scaled 10e18, so include extra scale in numerator dividing asset to keep it there */ uint256 tokenAmount = availableBorrow.mul(expScale).div(assetPrice); uint256 borrowStatus = compoundMoneyMarket.borrow( address(borrowedToken), tokenAmount ); require(borrowStatus == 0, "borrow failed"); /* ---------- sweep tokens to user ------------- */ uint256 borrowedTokenBalance = borrowedToken.balanceOf(address(this)); borrowedToken.transfer(owner, borrowedTokenBalance); } /* @dev the factory contract will transfer tokens necessary to repay */ function repay() external { require(creator == msg.sender); uint256 repayStatus = compoundMoneyMarket.repayBorrow( address(borrowedToken), uint256(-1) ); require(repayStatus == 0, "repay failed"); /* ---------- withdraw excess collateral weth ------- */ uint256 collateralRatio = compoundMoneyMarket.collateralRatio(); (uint256 status, uint256 totalSupply, uint256 totalBorrow) = compoundMoneyMarket .calculateAccountValues(address(this)); require(status == 0, "calculating account values failed"); uint256 amountToWithdraw; if (totalBorrow == 0) { amountToWithdraw = uint256(-1); } else { amountToWithdraw = findAvailableWithdrawal( totalSupply, totalBorrow, collateralRatio ); } uint256 withdrawStatus = compoundMoneyMarket.withdraw( address(weth), amountToWithdraw ); require(withdrawStatus == 0, "withdrawal failed"); /* ---------- return ether to user ---------*/ uint256 wethBalance = weth.balanceOf(address(this)); weth.withdraw(wethBalance); owner.transfer(address(this).balance); } /* @dev returns borrow value in eth scaled to 10e18 */ function findAvailableBorrow( uint256 currentSupplyValue, uint256 currentBorrowValue, uint256 collateralRatio ) public pure returns (uint256) { uint256 totalPossibleBorrow = currentSupplyValue.mul(expScale).div( collateralRatio.add(collateralRatioBuffer) ); if (totalPossibleBorrow > currentBorrowValue) { return totalPossibleBorrow.sub(currentBorrowValue).div(expScale); } else { return 0; } } /* @dev returns available withdrawal in eth scale to 10e18 */ function findAvailableWithdrawal( uint256 currentSupplyValue, uint256 currentBorrowValue, uint256 collateralRatio ) public pure returns (uint256) { uint256 requiredCollateralValue = currentBorrowValue .mul(collateralRatio.add(collateralRatioBuffer)) .div(expScale); if (currentSupplyValue > requiredCollateralValue) { return currentSupplyValue.sub(requiredCollateralValue).div(expScale); } else { return 0; } } /* @dev it is necessary to accept eth to unwrap weth */ function() external payable {} }
the factory contract will transfer tokens necessary to repay / ---------- withdraw excess collateral weth ------- /
function repay() external { require(creator == msg.sender); uint256 repayStatus = compoundMoneyMarket.repayBorrow( address(borrowedToken), uint256(-1) ); require(repayStatus == 0, "repay failed"); uint256 collateralRatio = compoundMoneyMarket.collateralRatio(); (uint256 status, uint256 totalSupply, uint256 totalBorrow) = compoundMoneyMarket .calculateAccountValues(address(this)); require(status == 0, "calculating account values failed"); uint256 amountToWithdraw; if (totalBorrow == 0) { amountToWithdraw = uint256(-1); amountToWithdraw = findAvailableWithdrawal( totalSupply, totalBorrow, collateralRatio ); } uint256 withdrawStatus = compoundMoneyMarket.withdraw( address(weth), amountToWithdraw ); require(withdrawStatus == 0, "withdrawal failed"); weth.withdraw(wethBalance); owner.transfer(address(this).balance); }
6,464,591
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title TurnBasedGameLobby /// @author Milton Jonathan pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./TurnBasedGame.sol"; /// @title TurnBasedGameLobby /// @notice Entry point for players to join games handled by the TurnBasedGame contract contract TurnBasedGameLobby { // max number of tokens uint256 public constant MAX_TOKEN_AMOUNT = type(uint256).max; // address for the allowed token provider address allowedERC20Address; // TurnBasedGame contract used for starting games TurnBasedGame turnBasedGame; // records queue information struct QueuedPlayer { address addr; uint256 funds; bytes info; } mapping(bytes32 => QueuedPlayer[]) internal queues; /// @notice Constructor /// @param _allowedERC20Address address of the ERC20 compatible token provider /// @param _turnBasedGameAddress address of the TurnBasedGame contract used for starting games constructor(address _allowedERC20Address, address _turnBasedGameAddress) { allowedERC20Address = _allowedERC20Address; turnBasedGame = TurnBasedGame(_turnBasedGameAddress); // approve game contract to spend tokens on behalf of lobby IERC20 tokenContract = IERC20(allowedERC20Address); tokenContract.approve(_turnBasedGameAddress, MAX_TOKEN_AMOUNT); } /// @notice Retrieves the current queue for a given game (specified by its template hash, metadata and number of players) /// @param _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic) /// @param _gameMetadata game-specific initial metadata/parameters /// @param _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed /// @param _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit) /// @param _gameNumPlayers number of players in the game /// @param _gameMinFunds minimum funds required to be staked in order to join the game /// @param _gameERC20Address address for a ERC20 compatible token provider /// @return array of QueuedPlayer structs representing the currently enqueued players for the specified game function getQueue( bytes32 _gameTemplateHash, bytes memory _gameMetadata, address[] memory _gameValidators, uint256 _gameTimeout, uint8 _gameNumPlayers, uint256 _gameMinFunds, address _gameERC20Address ) public view returns (QueuedPlayer[] memory) { // builds hash for game specification bytes32 queueHash = keccak256( abi.encodePacked( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameNumPlayers, _gameMinFunds, _gameERC20Address ) ); // retrieves queued players for given game specification return queues[queueHash]; } /// @notice Allows a player to remove himself from a game queue /// @param _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic) /// @param _gameMetadata game-specific initial metadata/parameters /// @param _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed /// @param _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit) /// @param _gameNumPlayers number of players in the game /// @param _gameMinFunds minimum funds required to be staked in order to join the game /// @param _gameERC20Address address for a ERC20 compatible token provider function leaveQueue( bytes32 _gameTemplateHash, bytes memory _gameMetadata, address[] memory _gameValidators, uint256 _gameTimeout, uint8 _gameNumPlayers, uint256 _gameMinFunds, address _gameERC20Address ) public { // builds hash for game specification bytes32 queueHash = keccak256( abi.encodePacked( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameNumPlayers, _gameMinFunds, _gameERC20Address ) ); // retrieves queued players for given game specification QueuedPlayer[] storage queuedPlayers = queues[queueHash]; // removes player from the queue for (uint256 i = 0; i < queuedPlayers.length; i++) { if (queuedPlayers[i].addr == msg.sender) { // found player: remove him and return funds uint256 playerFunds = queuedPlayers[i].funds; queuedPlayers[i] = queuedPlayers[queuedPlayers.length - 1]; queuedPlayers.pop(); returnFunds(IERC20(_gameERC20Address), msg.sender, playerFunds); break; } } } /// @notice Allows a player to join a game. People are queued up as they join and the game starts when enough people are available. /// @param _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic) /// @param _gameMetadata game-specific initial metadata/parameters /// @param _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed /// @param _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit) /// @param _gameNumPlayers number of players in the game /// @param _gameMinFunds minimum funds required to be staked in order to join the game /// @param _gameERC20Address address for a ERC20 compatible token provider /// @param _playerFunds amount being staked by the player joining the game /// @param _playerInfo game-specific information for the player joining the game function joinGame( bytes32 _gameTemplateHash, bytes memory _gameMetadata, address[] memory _gameValidators, uint256 _gameTimeout, uint8 _gameNumPlayers, uint256 _gameMinFunds, address _gameERC20Address, uint256 _playerFunds, bytes memory _playerInfo ) public { // ensures player is staking enough funds to participate in the game require(_playerFunds >= _gameMinFunds, "Player's staked funds is insufficient to join the game"); // ensures that the token provider is the allowed one require(_gameERC20Address == allowedERC20Address, "Unexpected token provider"); // builds hash for game specification bytes32 queueHash = keccak256( abi.encodePacked( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameNumPlayers, _gameMinFunds, _gameERC20Address ) ); // retrieves queued players for given game specification QueuedPlayer[] storage queuedPlayers = queues[queueHash]; // reverts if player is already in the queue for (uint256 i = 0; i < queuedPlayers.length; i++) { require(queuedPlayers[i].addr != msg.sender, "Player has already been enqueued to join this game"); } // lock player tokens in the lobby lockFunds(IERC20(_gameERC20Address), msg.sender, _playerFunds); if (queuedPlayers.length < _gameNumPlayers - 1) { // not enough players queued yet, so we simply add this new one to the queue QueuedPlayer memory newPlayer; newPlayer.addr = msg.sender; newPlayer.funds = _playerFunds; newPlayer.info = _playerInfo; queuedPlayers.push(newPlayer); } else { // enough players are already queued: we can start a game startGame( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameERC20Address, queuedPlayers, _playerFunds, _playerInfo ); // clears up queue delete queues[queueHash]; } } /// @notice Starts a game with the provided queuedPlayers + a new player who just joined. /// @param _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic) /// @param _gameMetadata game-specific initial metadata/parameters /// @param _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed /// @param _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit) /// @param _gameERC20Address address for a ERC20 compatible token provider /// @param _queuedPlayers an array of QueuedPlayer entries /// @param _newPlayerFunds amount being staked by the new player who just joined the game /// @param _newPlayerInfo game-specific information for the new player who just joined the game function startGame( bytes32 _gameTemplateHash, bytes memory _gameMetadata, address[] memory _gameValidators, uint256 _gameTimeout, address _gameERC20Address, QueuedPlayer[] storage _queuedPlayers, uint256 _newPlayerFunds, bytes memory _newPlayerInfo ) internal { // creates arrays of player data address[] memory players = new address[](_queuedPlayers.length + 1); uint256[] memory playerFunds = new uint256[](_queuedPlayers.length + 1); bytes[] memory playerInfos = new bytes[](_queuedPlayers.length + 1); // collects new player + previously queued players in pseudo-random order // obs: an alternative Lobby implementation for high-profile games could use a real VRF and charge appropriate fees for that uint256 posNew = uint256(keccak256(abi.encodePacked(block.timestamp))) % (_queuedPlayers.length + 1); players[posNew] = msg.sender; playerFunds[posNew] = _newPlayerFunds; playerInfos[posNew] = _newPlayerInfo; for (uint256 i = 0; i < _queuedPlayers.length; i++) { uint256 pos = i + uint256(keccak256(abi.encodePacked(block.timestamp))) % (_queuedPlayers.length - i); if (pos >= posNew) { pos = pos + 1; } players[pos] = _queuedPlayers[i].addr; playerFunds[pos] = _queuedPlayers[i].funds; playerInfos[pos] = _queuedPlayers[i].info; } // starts game turnBasedGame.startGame( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameERC20Address, players, playerFunds, playerInfos ); } /// @notice Lock player tokens in the lobby contract until the game start /// @param _tokenProvider ERC20 compatible token provider instance /// @param _playerAddress address for the player whose tokens will be locked in lobby account /// @param _playerFunds amount being staked by the player joining the game function lockFunds( IERC20 _tokenProvider, address _playerAddress, uint256 _playerFunds ) internal { _tokenProvider.transferFrom(_playerAddress, address(this), _playerFunds); } /// @notice Return player tokens from the lobby contract to the given address /// @param _tokenProvider ERC20 compatible token provider instance /// @param _playerAddress address for the player whose tokens will be returned from the lobby account /// @param _playerFunds amount to return to the player function returnFunds( IERC20 _tokenProvider, address _playerAddress, uint256 _playerFunds ) internal { _tokenProvider.transfer(_playerAddress, _playerFunds); } }
Allows a player to remove himself from a game queue _gameTemplateHash template hash for the Cartesi Machine computation that verifies the game (identifies the game computation/logic) _gameMetadata game-specific initial metadata/parameters _gameValidators addresses of the validator nodes that will run a Descartes verification should it be needed _gameTimeout global timeout for game activity in seconds, after which the game may be terminated (zero means there is no timeout limit) _gameNumPlayers number of players in the game _gameMinFunds minimum funds required to be staked in order to join the game _gameERC20Address address for a ERC20 compatible token provider builds hash for game specification retrieves queued players for given game specification removes player from the queue found player: remove him and return funds
function leaveQueue( bytes32 _gameTemplateHash, bytes memory _gameMetadata, address[] memory _gameValidators, uint256 _gameTimeout, uint8 _gameNumPlayers, uint256 _gameMinFunds, address _gameERC20Address ) public { bytes32 queueHash = keccak256( abi.encodePacked( _gameTemplateHash, _gameMetadata, _gameValidators, _gameTimeout, _gameNumPlayers, _gameMinFunds, _gameERC20Address ) ); QueuedPlayer[] storage queuedPlayers = queues[queueHash]; for (uint256 i = 0; i < queuedPlayers.length; i++) { if (queuedPlayers[i].addr == msg.sender) { uint256 playerFunds = queuedPlayers[i].funds; queuedPlayers[i] = queuedPlayers[queuedPlayers.length - 1]; queuedPlayers.pop(); returnFunds(IERC20(_gameERC20Address), msg.sender, playerFunds); break; } } }
13,116,082
/** *Submitted for verification at Etherscan.io on 2021-05-17 */ // File: contracts/interface/ICoFiXV2VaultForTrader.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.6.12; interface ICoFiXV2VaultForTrader { event RouterAllowed(address router); event RouterDisallowed(address router); event ClearPendingRewardOfCNode(uint256 pendingAmount); event ClearPendingRewardOfLP(uint256 pendingAmount); function setGovernance(address gov) external; function setCofiRate(uint256 cofiRate) external; function allowRouter(address router) external; function disallowRouter(address router) external; function calcMiningRate(address pair, uint256 neededETHAmount) external view returns (uint256); function calcNeededETHAmountForAdjustment(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256); function actualMiningAmount(address pair, uint256 reserve0, uint256 reserve1, uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 amount, uint256 totalAccruedAmount, uint256 neededETHAmount); function distributeReward(address pair, uint256 ethAmount, uint256 erc20Amount, address rewardTo) external; function clearPendingRewardOfCNode() external; function clearPendingRewardOfLP(address pair) external; function getPendingRewardOfCNode() external view returns (uint256); function getPendingRewardOfLP(address pair) external view returns (uint256); } // File: contracts/interface/ICoFiXStakingRewards.sol pragma solidity 0.6.12; interface ICoFiXStakingRewards { // Views /// @dev The rewards vault contract address set in factory contract /// @return Returns the vault address function rewardsVault() external view returns (address); /// @dev The lastBlock reward applicable /// @return Returns the latest block.number on-chain function lastBlockRewardApplicable() external view returns (uint256); /// @dev Reward amount represents by per staking token function rewardPerToken() external view returns (uint256); /// @dev How many reward tokens a user has earned but not claimed at present /// @param account The target account /// @return The amount of reward tokens a user earned function earned(address account) external view returns (uint256); /// @dev How many reward tokens accrued recently /// @return The amount of reward tokens accrued recently function accrued() external view returns (uint256); /// @dev Get the latest reward rate of this mining pool (tokens amount per block) /// @return The latest reward rate function rewardRate() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited into to this reward pool (mining pool) /// @return The total amount of XTokens deposited in this mining pool function totalSupply() external view returns (uint256); /// @dev How many stakingToken (XToken) deposited by the target account /// @param account The target account /// @return The total amount of XToken deposited in this mining pool function balanceOf(address account) external view returns (uint256); /// @dev Get the address of token for staking in this mining pool /// @return The staking token address function stakingToken() external view returns (address); /// @dev Get the address of token for rewards in this mining pool /// @return The rewards token address function rewardsToken() external view returns (address); // Mutative /// @dev Stake/Deposit into the reward pool (mining pool) /// @param amount The target amount function stake(uint256 amount) external; /// @dev Stake/Deposit into the reward pool (mining pool) for other account /// @param other The target account /// @param amount The target amount function stakeForOther(address other, uint256 amount) external; /// @dev Withdraw from the reward pool (mining pool), get the original tokens back /// @param amount The target amount function withdraw(uint256 amount) external; /// @dev Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() external; /// @dev Claim the reward the user earned function getReward() external; function getRewardAndStake() external; /// @dev User exit the reward pool, it's actually withdraw and getReward function exit() external; /// @dev Add reward to the mining pool function addReward(uint256 amount) external; // Events event RewardAdded(address sender, uint256 reward); event Staked(address indexed user, uint256 amount); event StakedForOther(address indexed user, address indexed other, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); } // File: contracts/interface/ICoFiXVaultForLP.sol pragma solidity 0.6.12; interface ICoFiXVaultForLP { enum POOL_STATE {INVALID, ENABLED, DISABLED} event NewPoolAdded(address pool, uint256 index); event PoolEnabled(address pool); event PoolDisabled(address pool); function setGovernance(address _new) external; function setInitCoFiRate(uint256 _new) external; function setDecayPeriod(uint256 _new) external; function setDecayRate(uint256 _new) external; function addPool(address pool) external; function enablePool(address pool) external; function disablePool(address pool) external; function setPoolWeight(address pool, uint256 weight) external; function batchSetPoolWeight(address[] memory pools, uint256[] memory weights) external; function distributeReward(address to, uint256 amount) external; function getPendingRewardOfLP(address pair) external view returns (uint256); function currentPeriod() external view returns (uint256); function currentCoFiRate() external view returns (uint256); function currentPoolRate(address pool) external view returns (uint256 poolRate); function currentPoolRateByPair(address pair) external view returns (uint256 poolRate); /// @dev Get the award staking pool address of pair (XToken) /// @param pair The address of XToken(pair) contract /// @return pool The pool address function stakingPoolForPair(address pair) external view returns (address pool); function getPoolInfo(address pool) external view returns (POOL_STATE state, uint256 weight); function getPoolInfoByPair(address pair) external view returns (POOL_STATE state, uint256 weight); function getEnabledPoolCnt() external view returns (uint256); function getCoFiStakingPool() external view returns (address pool); } // File: contracts/interface/ICoFiXERC20.sol pragma solidity 0.6.12; interface ICoFiXERC20 { 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; } // File: contracts/interface/ICoFiXV2Pair.sol pragma solidity 0.6.12; interface ICoFiXV2Pair is ICoFiXERC20 { struct OraclePrice { uint256 ethAmount; uint256 erc20Amount; uint256 blockNum; uint256 K; uint256 theta; } // All pairs: {ETH <-> ERC20 Token} event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, address outToken, uint outAmount, address indexed to); event Swap( address indexed sender, uint amountIn, uint amountOut, address outToken, 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); function mint(address to, uint amountETH, uint amountToken) external payable returns (uint liquidity, uint oracleFeeChange); function burn(address tokenTo, address ethTo) external payable returns (uint amountTokenOut, uint amountETHOut, uint oracleFeeChange); function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[5] memory tradeInfo); // function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo); function skim(address to) external; function sync() external; function initialize(address, address, string memory, string memory, uint256, uint256) external; /// @dev get Net Asset Value Per Share /// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token} /// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token} /// @return navps The Net Asset Value Per Share (liquidity) represents function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps); /// @dev get initial asset ratio /// @return _initToken0Amount Token0(ETH) side of initial asset ratio {ETH <-> ERC20 Token} /// @return _initToken1Amount Token1(ERC20) side of initial asset ratio {ETH <-> ERC20 Token} function getInitialAssetRatio() external view returns (uint256 _initToken0Amount, uint256 _initToken1Amount); } // File: contracts/interface/IWETH.sol pragma solidity 0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; function balanceOf(address account) external view returns (uint); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interface/ICoFiXV2Router.sol pragma solidity 0.6.12; interface ICoFiXV2Router { function factory() external pure returns (address); function WETH() external pure returns (address); enum DEX_TYPE { COFIX, UNISWAP } // All pairs: {ETH <-> ERC20 Token} /// @dev Maker add liquidity to pool, get pool token (mint XToken to maker) (notice: msg.value = amountETH + oracle fee) /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The dealine of this request /// @return liquidity The real liquidity or XToken minted from pool function addLiquidity( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); /// @dev Maker add liquidity to pool, get pool token (mint XToken) and stake automatically (notice: msg.value = amountETH + oracle fee) /// @param token The address of ERC20 Token /// @param amountETH The amount of ETH added to pool /// @param amountToken The amount of Token added to pool /// @param liquidityMin The minimum liquidity maker wanted /// @param to The target address receiving the liquidity pool (XToken) /// @param deadline The dealine of this request /// @return liquidity The real liquidity or XToken minted from pool function addLiquidityAndStake( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external payable returns (uint liquidity); /// @dev Maker remove liquidity from pool to get ERC20 Token and ETH back (maker burn XToken) (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param liquidity The amount of liquidity (XToken) sent to pool, or the liquidity to remove /// @param amountETHMin The minimum amount of ETH wanted to get from pool /// @param to The target address receiving the Token /// @param deadline The dealine of this request /// @return amountToken The real amount of Token transferred from the pool /// @return amountETH The real amount of ETH transferred from the pool function removeLiquidityGetTokenAndETH( address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH); /// @dev Trader swap exact amount of ETH for ERC20 Tokens (notice: msg.value = amountIn + oracle fee) /// @param token The address of ERC20 Token /// @param amountIn The exact amount of ETH a trader want to swap into pool /// @param amountOutMin The minimum amount of Token a trader want to swap out of pool /// @param to The target address receiving the Token /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of ETH transferred into pool /// @return _amountOut The real amount of Token transferred out of pool function swapExactETHForTokens( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap exact amount of ERC20 Tokens for ETH (notice: msg.value = oracle fee) /// @param token The address of ERC20 Token /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the ETH /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of Token transferred into pool /// @return _amountOut The real amount of ETH transferred out of pool function swapExactTokensForETH( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Trader swap exact amount of ERC20 Tokens for other ERC20 Tokens (notice: msg.value = oracle fee) /// @param tokenIn The address of ERC20 Token a trader want to swap into pool /// @param tokenOut The address of ERC20 Token a trader want to swap out of pool /// @param amountIn The exact amount of Token a trader want to swap into pool /// @param amountOutMin The mininum amount of ETH a trader want to swap out of pool /// @param to The target address receiving the Token /// @param rewardTo The target address receiving the CoFi Token as rewards /// @param deadline The dealine of this request /// @return _amountIn The real amount of Token transferred into pool /// @return _amountOut The real amount of Token transferred out of pool function swapExactTokensForTokens( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external payable returns (uint _amountIn, uint _amountOut); /// @dev Swaps an exact amount of input tokens for as many output tokens as possible, along the route determined by the path. The first element of path is the input token, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist). `msg.sender` should have already given the router an allowance of at least amountIn on the input token. The swap execution can be done via cofix or uniswap. That's why it's called hybrid. /// @param amountIn The amount of input tokens to send. /// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert. /// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity. /// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap. /// @param to Recipient of the output tokens. /// @param rewardTo The target address receiving the CoFi Token as rewards. /// @param deadline Unix timestamp after which the transaction will revert. /// @return amounts The input token amount and all subsequent output token amounts. function hybridSwapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external payable returns (uint[] memory amounts); /// @dev Swaps an exact amount of ETH for as many output tokens as possible, along the route determined by the path. The first element of path must be WETH, the last is the output token, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist). /// @param amountIn The amount of input tokens to send. /// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert. /// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity. /// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap. /// @param to Recipient of the output tokens. /// @param rewardTo The target address receiving the CoFi Token as rewards. /// @param deadline Unix timestamp after which the transaction will revert. /// @return amounts The input token amount and all subsequent output token amounts. function hybridSwapExactETHForTokens( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external payable returns (uint[] memory amounts); /// @dev Swaps an exact amount of tokens for as much ETH as possible, along the route determined by the path. The first element of path is the input token, the last must be WETH, and any intermediate elements represent intermediate pairs to trade through (if, for example, a direct pair does not exist). If the to address is a smart contract, it must have the ability to receive ETH. /// @param amountIn The amount of input tokens to send. /// @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert. /// @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of addresses must exist and have liquidity. /// @param dexes An array of dex type values, specifying the exchanges to be used, e.g. CoFiX, Uniswap. /// @param to Recipient of the output tokens. /// @param rewardTo The target address receiving the CoFi Token as rewards. /// @param deadline Unix timestamp after which the transaction will revert. /// @return amounts The input token amount and all subsequent output token amounts. function hybridSwapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external payable returns (uint[] memory amounts); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/lib/UniswapV2Library.sol pragma solidity 0.6.12; interface IUniswapV2Pair { function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, '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(uint(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 (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint 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(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint 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(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // File: contracts/lib/TransferHelper.sol pragma solidity 0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/interface/ICoFiXV2Factory.sol pragma solidity 0.6.12; interface ICoFiXV2Factory { // All pairs: {ETH <-> ERC20 Token} event PairCreated(address indexed token, address pair, uint256); event NewGovernance(address _new); event NewController(address _new); event NewFeeReceiver(address _new); event NewFeeVaultForLP(address token, address feeVault); event NewVaultForLP(address _new); event NewVaultForTrader(address _new); event NewVaultForCNode(address _new); event NewDAO(address _new); /// @dev Create a new token pair for trading /// @param token the address of token to trade /// @param initToken0Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @param initToken1Amount the initial asset ratio (initToken0Amount:initToken1Amount) /// @return pair the address of new token pair function createPair( address token, uint256 initToken0Amount, uint256 initToken1Amount ) external returns (address pair); function getPair(address token) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function getTradeMiningStatus(address token) external view returns (bool status); function setTradeMiningStatus(address token, bool status) external; function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs function setFeeVaultForLP(address token, address feeVault) external; function setGovernance(address _new) external; function setController(address _new) external; function setFeeReceiver(address _new) external; function setVaultForLP(address _new) external; function setVaultForTrader(address _new) external; function setVaultForCNode(address _new) external; function setDAO(address _new) external; function getController() external view returns (address controller); function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders function getVaultForLP() external view returns (address vaultForLP); function getVaultForTrader() external view returns (address vaultForTrader); function getVaultForCNode() external view returns (address vaultForCNode); function getDAO() external view returns (address dao); } // File: contracts/CoFiXV2Router.sol pragma solidity 0.6.12; // Router contract to interact with each CoFiXPair, no owner or governance contract CoFiXV2Router is ICoFiXV2Router { using SafeMath for uint; address public immutable override factory; address public immutable uniFactory; address public immutable override WETH; uint256 internal constant NEST_ORACLE_FEE = 0.01 ether; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'CRouter: EXPIRED'); _; } constructor(address _factory, address _uniFactory, address _WETH) public { factory = _factory; uniFactory = _uniFactory; WETH = _WETH; } receive() external payable {} // calculates the CREATE2 address for a pair without making any external calls function pairFor(address _factory, address token) internal view returns (address pair) { // pair = address(uint(keccak256(abi.encodePacked( // hex'ff', // _factory, // keccak256(abi.encodePacked(token)), // hex'fb0c5470b7fbfce7f512b5035b5c35707fd5c7bd43c8d81959891b0296030118' // init code hash // )))); // calc the real init code hash, not suitable for us now, could use this in the future return ICoFiXV2Factory(_factory).getPair(token); } // msg.value = amountETH + oracle fee function addLiquidity( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint liquidity) { require(msg.value > amountETH, "CRouter: insufficient msg.value"); uint256 _oracleFee = msg.value.sub(amountETH); address pair = pairFor(factory, token); if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); } if (amountETH > 0) { IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); } uint256 oracleFeeChange; (liquidity, oracleFeeChange) = ICoFiXV2Pair(pair).mint{value: _oracleFee}(to, amountETH, amountToken); require(liquidity >= liquidityMin, "CRouter: less liquidity than expected"); // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } // msg.value = amountETH + oracle fee function addLiquidityAndStake( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint liquidity) { // must create a pair before using this function require(msg.value > amountETH, "CRouter: insufficient msg.value"); uint256 _oracleFee = msg.value.sub(amountETH); address pair = pairFor(factory, token); require(pair != address(0), "CRouter: invalid pair"); if (amountToken > 0 ) { // support for tokens which do not allow to transfer zero values TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); } if (amountETH > 0) { IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); } uint256 oracleFeeChange; (liquidity, oracleFeeChange) = ICoFiXV2Pair(pair).mint{value: _oracleFee}(address(this), amountETH, amountToken); require(liquidity >= liquidityMin, "CRouter: less liquidity than expected"); // find the staking rewards pool contract for the liquidity token (pair) address pool = ICoFiXVaultForLP(ICoFiXV2Factory(factory).getVaultForLP()).stakingPoolForPair(pair); require(pool != address(0), "CRouter: invalid staking pool"); // approve to staking pool ICoFiXV2Pair(pair).approve(pool, liquidity); ICoFiXStakingRewards(pool).stakeForOther(to, liquidity); ICoFiXV2Pair(pair).approve(pool, 0); // ensure // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } // msg.value = oracle fee function removeLiquidityGetTokenAndETH( address token, uint liquidity, uint amountETHMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint amountToken, uint amountETH) { require(msg.value > 0, "CRouter: insufficient msg.value"); address pair = pairFor(factory, token); ICoFiXV2Pair(pair).transferFrom(msg.sender, pair, liquidity); uint oracleFeeChange; (amountToken, amountETH, oracleFeeChange) = ICoFiXV2Pair(pair).burn{value: msg.value}(to, address(this)); require(amountETH >= amountETHMin, "CRouter: got less than expected"); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } // msg.value = amountIn + oracle fee function swapExactETHForTokens( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > amountIn, "CRouter: insufficient msg.value"); IWETH(WETH).deposit{value: amountIn}(); address pair = pairFor(factory, token); assert(IWETH(WETH).transfer(pair, amountIn)); uint oracleFeeChange; uint256[5] memory tradeInfo; (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{ value: msg.value.sub(amountIn)}(token, to); require(_amountOut >= amountOutMin, "CRouter: got less than expected"); // distribute trading rewards - CoFi! address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo); } // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } // msg.value = oracle fee function swapExactTokensForTokens( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > 0, "CRouter: insufficient msg.value"); address[2] memory pairs; // [pairIn, pairOut] // swapExactTokensForETH pairs[0] = pairFor(factory, tokenIn); TransferHelper.safeTransferFrom(tokenIn, msg.sender, pairs[0], amountIn); uint oracleFeeChange; uint256[5] memory tradeInfo; (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[0]).swapWithExact{value: msg.value}(WETH, address(this)); // distribute trading rewards - CoFi! address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[0], tradeInfo[1], tradeInfo[2], rewardTo); } // swapExactETHForTokens pairs[1] = pairFor(factory, tokenOut); assert(IWETH(WETH).transfer(pairs[1], _amountOut)); // swap with all amountOut in last swap (, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[1]).swapWithExact{value: oracleFeeChange}(tokenOut, to); require(_amountOut >= amountOutMin, "CRouter: got less than expected"); // distribute trading rewards - CoFi! if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[1], tradeInfo[1], tradeInfo[2], rewardTo); } // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } // msg.value = oracle fee function swapExactTokensForETH( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > 0, "CRouter: insufficient msg.value"); address pair = pairFor(factory, token); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountIn); uint oracleFeeChange; uint256[5] memory tradeInfo; (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{value: msg.value}(WETH, address(this)); require(_amountOut >= amountOutMin, "CRouter: got less than expected"); IWETH(WETH).withdraw(_amountOut); TransferHelper.safeTransferETH(to, _amountOut); // distribute trading rewards - CoFi! address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo); } // refund oracle fee to msg.sender, if any if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); } function hybridSwapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint[] memory amounts) { // fast check require(path.length >= 2, "CRouter: invalid path"); require(dexes.length == path.length - 1, "CRouter: invalid dexes"); _checkOracleFee(dexes, msg.value); // send amountIn to the first pair TransferHelper.safeTransferFrom( path[0], msg.sender, getPairForDEX(path[0], path[1], dexes[0]), amountIn ); // exec hybridSwap amounts = new uint[](path.length); amounts[0] = amountIn; _hybridSwap(path, dexes, amounts, to, rewardTo); // check amountOutMin in the last require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount "); } function hybridSwapExactETHForTokens( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint[] memory amounts) { // fast check require(path.length >= 2 && path[0] == WETH, "CRouter: invalid path"); require(dexes.length == path.length - 1, "CRouter: invalid dexes"); _checkOracleFee(dexes, msg.value.sub(amountIn)); // would revert if msg.value is less than amountIn // convert ETH and send amountIn to the first pair IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(getPairForDEX(path[0], path[1], dexes[0]), amountIn)); // exec hybridSwap amounts = new uint[](path.length); amounts[0] = amountIn; _hybridSwap(path, dexes, amounts, to, rewardTo); // check amountOutMin in the last require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount "); } function hybridSwapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, DEX_TYPE[] calldata dexes, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint[] memory amounts) { // fast check require(path.length >= 2 && path[path.length - 1] == WETH, "CRouter: invalid path"); require(dexes.length == path.length - 1, "CRouter: invalid dexes"); _checkOracleFee(dexes, msg.value); // send amountIn to the first pair TransferHelper.safeTransferFrom( path[0], msg.sender, getPairForDEX(path[0], path[1], dexes[0]), amountIn ); // exec hybridSwap amounts = new uint[](path.length); amounts[0] = amountIn; _hybridSwap(path, dexes, amounts, address(this), rewardTo); // check amountOutMin in the last require(amounts[amounts.length - 1] >= amountOutMin, "CRouter: insufficient output amount "); // convert WETH IWETH(WETH).withdraw(amounts[amounts.length - 1]); TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); } function _checkOracleFee(DEX_TYPE[] memory dexes, uint256 oracleFee) internal pure { uint cofixCnt; for (uint i; i < dexes.length; i++) { if (dexes[i] == DEX_TYPE.COFIX) { cofixCnt++; } } // strict check here // to simplify the verify logic for oracle fee and prevent user from locking oracle fee by mistake // if NEST_ORACLE_FEE value changed, this router would not work as expected // TODO: refund the oracle fee? require(oracleFee == NEST_ORACLE_FEE.mul(cofixCnt), "CRouter: wrong oracle fee"); } function _hybridSwap(address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to, address rewardTo) internal { for (uint i; i < path.length - 1; i++) { if (dexes[i] == DEX_TYPE.COFIX) { _swapOnCoFiX(i, path, dexes, amounts, _to, rewardTo); } else if (dexes[i] == DEX_TYPE.UNISWAP) { _swapOnUniswap(i, path, dexes, amounts, _to); } else { revert("CRouter: unknown dex"); } } } function _swapOnUniswap(uint i, address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to) internal { address pair = getPairForDEX(path[i], path[i + 1], DEX_TYPE.UNISWAP); (address token0,) = UniswapV2Library.sortTokens(path[i], path[i + 1]); { (uint reserveIn, uint reserveOut) = UniswapV2Library.getReserves(uniFactory, path[i], path[i + 1]); amounts[i + 1] = UniswapV2Library.getAmountOut(amounts[i], reserveIn, reserveOut); } uint amountOut = amounts[i + 1]; (uint amount0Out, uint amount1Out) = path[i] == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); address to; { if (i < path.length - 2) { to = getPairForDEX(path[i + 1], path[i + 2], dexes[i + 1]); } else { to = _to; } } IUniswapV2Pair(pair).swap( amount0Out, amount1Out, to, new bytes(0) ); } function _swapOnCoFiX(uint i, address[] memory path, DEX_TYPE[] memory dexes, uint[] memory amounts, address _to, address rewardTo) internal { address pair = getPairForDEX(path[i], path[i + 1], DEX_TYPE.COFIX); address to; if (i < path.length - 2) { to = getPairForDEX(path[i + 1], path[i + 2], dexes[i + 1]); } else { to = _to; } // TODO: dynamic oracle fee { uint256[5] memory tradeInfo; (,amounts[i+1],,tradeInfo) = ICoFiXV2Pair(pair).swapWithExact{value: NEST_ORACLE_FEE}(path[i + 1], to); // distribute trading rewards - CoFi! address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pair, tradeInfo[1], tradeInfo[2], rewardTo); } } } function isCoFiXNativeSupported(address input, address output) public view returns (bool supported, address pair) { // NO WETH included if (input != WETH && output != WETH) return (false, pair); if (input != WETH) { pair = pairFor(factory, input); } else if (output != WETH) { pair = pairFor(factory, output); } // if tokenIn & tokenOut are both WETH, then the pair is zero if (pair != address(0)) // TODO: add check for reserves supported = true; return (supported, pair); } function getPairForDEX(address input, address output, DEX_TYPE dex) public view returns (address pair) { if (dex == DEX_TYPE.COFIX) { bool supported; (supported, pair) = isCoFiXNativeSupported(input, output); if (!supported) { revert("CRouter: not available on CoFiX"); } } else if (dex == DEX_TYPE.UNISWAP) { pair = UniswapV2Library.pairFor(uniFactory, input, output); } else { revert("CRouter: unknown dex"); } } // TODO: not used currently function hybridPair(address input, address output) public view returns (bool useCoFiX, address pair) { (useCoFiX, pair) = isCoFiXNativeSupported(input, output); if (useCoFiX) { return (useCoFiX, pair); } return (false, UniswapV2Library.pairFor(uniFactory, input, output)); } }
msg.value = oracle fee swapExactTokensForETH distribute trading rewards - CoFi!
) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > 0, "CRouter: insufficient msg.value"); pairs[0] = pairFor(factory, tokenIn); TransferHelper.safeTransferFrom(tokenIn, msg.sender, pairs[0], amountIn); uint oracleFeeChange; uint256[5] memory tradeInfo; address vaultForTrader = ICoFiXV2Factory(factory).getVaultForTrader(); (_amountIn, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[0]).swapWithExact{value: msg.value}(WETH, address(this)); function swapExactTokensForTokens( address tokenIn, address tokenOut, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[0], tradeInfo[1], tradeInfo[2], rewardTo); } require(_amountOut >= amountOutMin, "CRouter: got less than expected"); pairs[1] = pairFor(factory, tokenOut); (, _amountOut, oracleFeeChange, tradeInfo) = ICoFiXV2Pair(pairs[1]).swapWithExact{value: oracleFeeChange}(tokenOut, to); if (tradeInfo[0] > 0 && rewardTo != address(0) && vaultForTrader != address(0)) { ICoFiXV2VaultForTrader(vaultForTrader).distributeReward(pairs[1], tradeInfo[1], tradeInfo[2], rewardTo); } if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange); }
6,573,599
pragma solidity ^0.4.13; /* taking ideas from FirstBlood token */ contract SafeMath { 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; } } /* * Ownable * * Base contract with an owner. * Provides onlyOwner modifier, which prevents function from running if it is called by anyone other than the owner. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } /* * Haltable * * Abstract contract that allows children to implement an * emergency stop mechanism. Differs from Pausable by causing a throw when in halt mode. * * * Originally envisioned in FirstBlood ICO contract. */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract FluencePreSale is Haltable, SafeMath { mapping (address => uint256) public balanceOf; /*/ * Constants /*/ string public constant name = "Fluence Presale Token"; string public constant symbol = "FPT"; uint public constant decimals = 18; // 6% of tokens uint256 public constant SUPPLY_LIMIT = 6000000 ether; // What is given to contributors, <= SUPPLY_LIMIT uint256 public totalSupply; // If soft cap is not reached, refund process is started uint256 public softCap = 1000 ether; // Basic price uint256 public constant basicThreshold = 500 finney; uint public constant basicTokensPerEth = 1500; // Advanced price uint256 public constant advancedThreshold = 5 ether; uint public constant advancedTokensPerEth = 2250; // Expert price uint256 public constant expertThreshold = 100 ether; uint public constant expertTokensPerEth = 3000; // As we have different prices for different amounts, // we keep a mapping of contributions to make refund mapping (address => uint256) public etherContributions; // Max balance of the contract uint256 public etherCollected; // Address to withdraw ether to address public beneficiary; uint public startAtBlock; uint public endAtBlock; // All tokens are sold event GoalReached(uint amountRaised); // Minimal ether cap collected event SoftCapReached(uint softCap); // New contribution received and tokens are issued event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount); // Ether is taken back event Refunded(address indexed holder, uint256 amount); // If soft cap is reached, withdraw should be available modifier softCapReached { if (etherCollected < softCap) { revert(); } assert(etherCollected >= softCap); _; } // Allow contribution only during presale modifier duringPresale { if (block.number < startAtBlock || block.number > endAtBlock || totalSupply >= SUPPLY_LIMIT) { revert(); } assert(block.number >= startAtBlock && block.number <= endAtBlock && totalSupply < SUPPLY_LIMIT); _; } // Allow withdraw only during refund modifier duringRefund { if(block.number <= endAtBlock || etherCollected >= softCap || this.balance == 0) { revert(); } assert(block.number > endAtBlock && etherCollected < softCap && this.balance > 0); _; } function FluencePreSale(uint _startAtBlock, uint _endAtBlock, uint softCapInEther){ require(_startAtBlock > 0 && _endAtBlock > 0); beneficiary = msg.sender; startAtBlock = _startAtBlock; endAtBlock = _endAtBlock; softCap = softCapInEther * 1 ether; } // Change beneficiary address function setBeneficiary(address to) onlyOwner external { require(to != address(0)); beneficiary = to; } // Withdraw contract's balance to beneficiary account function withdraw() onlyOwner softCapReached external { require(this.balance > 0); beneficiary.transfer(this.balance); } // Process contribution, issue tokens to user function contribute(address _address) private stopInEmergency duringPresale { if(msg.value < basicThreshold && owner != _address) { revert(); } assert(msg.value >= basicThreshold || owner == _address); // Minimal contribution uint256 tokensToIssue; if (msg.value >= expertThreshold) { tokensToIssue = safeMult(msg.value, expertTokensPerEth); } else if (msg.value >= advancedThreshold) { tokensToIssue = safeMult(msg.value, advancedTokensPerEth); } else { tokensToIssue = safeMult(msg.value, basicTokensPerEth); } assert(tokensToIssue > 0); totalSupply = safeAdd(totalSupply, tokensToIssue); // Goal is already reached, can't issue any more tokens if(totalSupply > SUPPLY_LIMIT) { revert(); } assert(totalSupply <= SUPPLY_LIMIT); // Saving ether contributions for the case of refund etherContributions[_address] = safeAdd(etherContributions[_address], msg.value); // Track ether before adding current contribution to notice the event of reaching soft cap uint collectedBefore = etherCollected; etherCollected = safeAdd(etherCollected, msg.value); // Tokens are issued balanceOf[_address] = safeAdd(balanceOf[_address], tokensToIssue); NewContribution(_address, tokensToIssue, msg.value); if (totalSupply == SUPPLY_LIMIT) { GoalReached(etherCollected); } if (etherCollected >= softCap && collectedBefore < softCap) { SoftCapReached(etherCollected); } } function() external payable { contribute(msg.sender); } function refund() stopInEmergency duringRefund external { uint tokensToBurn = balanceOf[msg.sender]; // Sender must have tokens require(tokensToBurn > 0); // Burn balanceOf[msg.sender] = 0; // User contribution amount uint amount = etherContributions[msg.sender]; // Amount must be positive -- refund is not processed yet assert(amount > 0); etherContributions[msg.sender] = 0; // Clear state // Reduce counters etherCollected = safeSubtract(etherCollected, amount); totalSupply = safeSubtract(totalSupply, tokensToBurn); // Process refund. In case of error, it will be thrown msg.sender.transfer(amount); Refunded(msg.sender, amount); } }
Withdraw contract's balance to beneficiary account
function withdraw() onlyOwner softCapReached external { require(this.balance > 0); beneficiary.transfer(this.balance); }
12,722,555
/** *Submitted for verification at Etherscan.io on 2021-04-10 */ // SPDX-License-Identifier: MIT pragma solidity =0.7.6; pragma experimental ABIEncoderV2; abstract contract IManager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract IVat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } abstract contract IGem { function dec() virtual public returns (uint); function gem() virtual public returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IDaiJoin { function vat() public virtual returns (IVat); function dai() public virtual returns (IGem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } interface IERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } abstract contract IWETH { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library Address { 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); } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // 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 div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _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) ); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { uint256 userAllowance = IERC20(_token).allowance(_from, address(this)); uint256 balance = getBalance(_token, _from); // pull max allowance amount if balance is bigger than allowance _amount = (balance > userAllowance) ? userAllowance : balance; } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } abstract contract IDFSRegistry { function getAddr(bytes32 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } /// @title A stateful contract that holds and can change owner/admin contract AdminVault { address public owner; address public admin; constructor() { owner = msg.sender; admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { require(admin == msg.sender, "msg.sender not admin"); owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { require(admin == msg.sender, "msg.sender not admin"); admin = _admin; } } /// @title AdminAuth Handles owner/admin privileges over smart contracts contract AdminAuth { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(0xCCf3d848e08b94478Ed8f46fFead3008faF581fD); modifier onlyOwner() { require(adminVault.owner() == msg.sender, "msg.sender not owner"); _; } modifier onlyAdmin() { require(adminVault.admin() == msg.sender, "msg.sender not admin"); _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log( address _contract, address _caller, string memory _logName, bytes memory _data ) public { emit LogEvent(_contract, _caller, _logName, _data); } } /// @title Stores all the important DFS addresses and can be changed (timelock) contract DFSRegistry is AdminAuth { DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_ENTRY_ALREADY_EXISTS = "Entry id already exists"; string public constant ERR_ENTRY_NON_EXISTENT = "Entry id doesn't exists"; string public constant ERR_ENTRY_NOT_IN_CHANGE = "Entry not in change process"; string public constant ERR_WAIT_PERIOD_SHORTER = "New wait period must be bigger"; string public constant ERR_CHANGE_NOT_READY = "Change not ready yet"; string public constant ERR_EMPTY_PREV_ADDR = "Previous addr is 0"; string public constant ERR_ALREADY_IN_CONTRACT_CHANGE = "Already in contract change"; string public constant ERR_ALREADY_IN_WAIT_PERIOD_CHANGE = "Already in wait period change"; struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes32 => Entry) public entries; mapping(bytes32 => address) public previousAddresses; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes32 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes32 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { require(!entries[_id].exists, ERR_ENTRY_ALREADY_EXISTS); entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); // Remember tha address so we can revert back to old addr if needed previousAddresses[_id] = _contractAddr; logger.Log( address(this), msg.sender, "AddNewContract", abi.encode(_id, _contractAddr, _waitPeriod) ); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(previousAddresses[_id] != address(0), ERR_EMPTY_PREV_ADDR); address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; logger.Log( address(this), msg.sender, "RevertToPreviousAddress", abi.encode(_id, currentAddr, previousAddresses[_id]) ); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes32 _id, address _newContractAddr) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inWaitPeriodChange, ERR_ALREADY_IN_WAIT_PERIOD_CHANGE); entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; logger.Log( address(this), msg.sender, "StartContractChange", abi.encode(_id, entries[_id].contractAddr, _newContractAddr) ); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; logger.Log( address(this), msg.sender, "ApproveContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inContractChange, ERR_ENTRY_NOT_IN_CHANGE); address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelContractChange", abi.encode(_id, oldContractAddr, entries[_id].contractAddr) ); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes32 _id, uint256 _newWaitPeriod) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(!entries[_id].inContractChange, ERR_ALREADY_IN_CONTRACT_CHANGE); pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; logger.Log( address(this), msg.sender, "StartWaitPeriodChange", abi.encode(_id, _newWaitPeriod) ); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); require( block.timestamp >= (entries[_id].changeStartTime + entries[_id].waitPeriod), // solhint-disable-line ERR_CHANGE_NOT_READY ); uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; logger.Log( address(this), msg.sender, "ApproveWaitPeriodChange", abi.encode(_id, oldWaitTime, entries[_id].waitPeriod) ); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes32 _id) public onlyOwner { require(entries[_id].exists, ERR_ENTRY_NON_EXISTENT); require(entries[_id].inWaitPeriodChange, ERR_ENTRY_NOT_IN_CHANGE); uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; logger.Log( address(this), msg.sender, "CancelWaitPeriodChange", abi.encode(_id, oldWaitPeriod, entries[_id].waitPeriod) ); } } /// @title Implements Action interface and common helpers for passing inputs abstract contract ActionBase is AdminAuth { address public constant REGISTRY_ADDR = 0xD6049E1F5F3EfF1F921f5532aF1A1632bA23929C; DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( 0x5c55B921f590a89C1Ebe84dF170E655a82b62126 ); string public constant ERR_SUB_INDEX_VALUE = "Wrong sub index value"; string public constant ERR_RETURN_INDEX_VALUE = "Wrong return index value"; /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the TaskExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes[] memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (uint)); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (address)); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = abi.decode(_subData[getSubIndex(_mapType)], (bytes32)); } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { require(isReturnInjection(_type), ERR_SUB_INDEX_VALUE); return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { require(_type >= SUB_MIN_INDEX_VALUE, ERR_RETURN_INDEX_VALUE); return (_type - SUB_MIN_INDEX_VALUE); } } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, ""); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, ""); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, ""); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { require(setCache(_cacheAddr), "Cache not set"); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract IJoin { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (IGem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } /// @title Helper methods for MCDSaverProxy contract McdHelper is DSMath { IVat public constant vat = IVat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); address public constant DAI_JOIN_ADDR = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant DAI_ADDR = 0x6B175474E89094C44Da98b954EedeAC495271d0F; /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad precision /// @param _wad The input number in wad precision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal precision /// @dev If token decimal is bigger than 18, function reverts /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** sub(18 , IJoin(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = IVat(_vat).dai(_urn); (, uint rate,,,) = IVat(_vat).ilks(_ilk); (, uint art) = IVat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = IVat(_vat).ilks(_ilk); (, uint art) = IVat(_vat).urns(_ilk, _urn); uint dai = IVat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; // handles precision error (off by 1 wei) daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == DAI_JOIN_ADDR) return false; // if coll is weth it's and eth type coll if (address(IJoin(_joinAddr).gem()) == TokenUtils.WETH_ADDR) { return true; } return false; } /// @notice Returns the underlying token address from the joinAddr /// @dev For eth based collateral returns 0xEee... not weth addr /// @param _joinAddr Join address to check function getTokenFromJoin(address _joinAddr) internal view returns (address) { // if it's dai_join_addr don't check gem() it will fail, return dai addr if (_joinAddr == DAI_JOIN_ADDR) { return DAI_ADDR; } return address(IJoin(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(IManager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(IManager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } /// @title Payback dai debt for a Maker vault contract McdPayback is ActionBase, McdHelper { using TokenUtils for address; /// @inheritdoc ActionBase function executeAction( bytes[] memory _callData, bytes[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable override returns (bytes32) { (uint256 vaultId, uint256 amount, address from, address mcdManager) = parseInputs(_callData); vaultId = _parseParamUint(vaultId, _paramMapping[0], _subData, _returnValues); amount = _parseParamUint(amount, _paramMapping[1], _subData, _returnValues); from = _parseParamAddr(from, _paramMapping[2], _subData, _returnValues); amount = _mcdPayback(vaultId, amount, from, mcdManager); return bytes32(amount); } /// @inheritdoc ActionBase function executeActionDirect(bytes[] memory _callData) public payable override { (uint256 vaultId, uint256 amount, address from, address mcdManager) = parseInputs(_callData); _mcdPayback(vaultId, amount, from, mcdManager); } /// @inheritdoc ActionBase function actionType() public pure override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// /// @notice Paybacks the debt for a specified vault /// @param _vaultId Id of the vault /// @param _amount Amount of dai to be payed back /// @param _from Where the Dai is pulled from /// @param _mcdManager The manager address we are using function _mcdPayback( uint256 _vaultId, uint256 _amount, address _from, address _mcdManager ) internal returns (uint256) { IManager mcdManager = IManager(_mcdManager); address urn = mcdManager.urns(_vaultId); bytes32 ilk = mcdManager.ilks(_vaultId); // if amount type(uint256).max payback the whole vault debt if (_amount == type(uint256).max) { _amount = getAllDebt(address(vat), urn, urn, ilk); } // pull Dai from user and join the maker pool DAI_ADDR.pullTokensIfNeeded(_from, _amount); DAI_ADDR.approveToken(DAI_JOIN_ADDR, _amount); IDaiJoin(DAI_JOIN_ADDR).join(urn, _amount); // decrease the vault debt mcdManager.frob(_vaultId, 0, normalizePaybackAmount(address(vat), urn, ilk)); logger.Log( address(this), msg.sender, "McdPayback", abi.encode(_vaultId, _amount, _from, _mcdManager) ); return _amount; } function parseInputs(bytes[] memory _callData) internal pure returns ( uint256 vaultId, uint256 amount, address from, address mcdManager ) { vaultId = abi.decode(_callData[0], (uint256)); amount = abi.decode(_callData[1], (uint256)); from = abi.decode(_callData[2], (address)); mcdManager = abi.decode(_callData[3], (address)); } }
@inheritdoc ActionBase
function executeActionDirect(bytes[] memory _callData) public payable override { (uint256 vaultId, uint256 amount, address from, address mcdManager) = parseInputs(_callData); _mcdPayback(vaultId, amount, from, mcdManager); }
2,117,288
./full_match/1/0x2D91D263909b589eDb18e66B9a157CB43619A875/sources/kali.sol
cannot realistically overflow on human timescales
function init( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32[16] memory govSettings_ ) public nonReentrant virtual { if (extensions_.length != extensionsData_.length) revert NoArrayParity(); if (votingPeriod != 0) revert Initialized(); if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds(); if (govSettings_[1] > 365 days) revert PeriodBounds(); if (govSettings_[2] > 100) revert QuorumMax(); if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds(); KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_); if (extensions_.length != 0) { unchecked { for (uint256 i; i < extensions_.length; i++) { extensions[extensions_[i]] = true; if (extensionsData_[i].length > 3) { (bool success, ) = extensions_[i].call(extensionsData_[i]); if (!success) revert InitCallFail(); } } } } docs = docs_; votingPeriod = govSettings_[0]; gracePeriod = govSettings_[1]; quorum = govSettings_[2]; supermajority = govSettings_[3]; proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]); proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]); proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]); proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]); proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]); proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]); proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]); proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]); proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]); proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]); proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]); } PROPOSAL LOGIC
8,319,411
pragma solidity ^ 0.5.1; contract ColorToken{ BondContract public bondContract; ResolveContract public resolveContract; address lastGateway; address communityResolve; address THIS = address(this); string public name = "Color Token"; string public symbol = "RGB"; uint8 constant public decimals = 18; uint _totalSupply; uint masternodeFee = 10; // 10% mapping(address => PyramidProxy) proxy; mapping(address => address) proxyOwner; mapping(address => uint256) public redBonds; mapping(address => uint256) public greenBonds; mapping(address => uint256) public blueBonds; mapping(address => uint256) public redResolves; mapping(address => uint256) public greenResolves; mapping(address => uint256) public blueResolves; mapping(address => mapping(address => uint)) approvals; mapping(address => address) gateway; mapping(address => uint256) public pocket; mapping(address => uint256) public upline; mapping(address => address) public minecart; mapping(address => address) public votingFor; mapping(address => uint256) public votesFor; constructor(address _bondContract) public{ bondContract = BondContract(_bondContract); resolveContract = ResolveContract( bondContract.getResolveContract() ); communityResolve = msg.sender; lastGateway = THIS; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint balance) { return proxy[_owner].getBalance(); } function max1(uint x) internal pure returns (uint){ if(x>1e18) return 1e18; else return x; } function ensureProxy(address addr) internal returns(address proxyAddr){ if( address(proxy[addr]) == 0x0000000000000000000000000000000000000000){ proxy[addr] = new PyramidProxy( this, bondContract ); proxyOwner[ address( proxy[addr] ) ] = addr; } return address( proxy[addr] ); } event Buy( address indexed addr, uint256 spent, uint256 bonds, uint red, uint green, uint blue); function buy(uint _red, uint _green, uint _blue) payable public { buy( msg.value, _red, _green, _blue, true); } function buy(uint ETH, uint _red, uint _green, uint _blue, bool EMIT) payable public returns(uint bondsCreated){ address sender = msg.sender; ensureProxy(sender); _red = max1(_red); _green = max1(_green); _blue = max1(_blue); uint fee = ETH / masternodeFee; uint eth4Bonds = ETH - fee; address payable proxyAddr = address( proxy[sender] ); proxyAddr.transfer(eth4Bonds); uint createdBonds = proxy[sender].buy(); bondsAddColor(sender,createdBonds, _red, _green, _blue); pocket[ gateway[sender] ] += fee/2; upline[ gateway[sender] ] += fee/2; pushMinecart(); if( EMIT ){ emit Buy( sender, ETH, createdBonds, _red, _green, _blue); } if( bondContract.balanceOf( address(proxy[sender]) ) > 10000*1e12 ){ lastGateway = sender; } return createdBonds; } function pushMinecart() internal{ pushMinecart(msg.sender); } function pushMinecart(address addr) internal{ if(gateway[addr] == 0x0000000000000000000000000000000000000000 || bondContract.balanceOf( address(proxy[ gateway[addr] ]) ) < 10000*1e12){ gateway[addr] = lastGateway; } if( minecart[addr] == THIS || minecart[addr] == 0x0000000000000000000000000000000000000000){ minecart[addr] = addr; }else{ minecart[addr] = gateway[ minecart[addr] ]; } address dropOff = minecart[addr]; pocket[ dropOff ] += upline[ dropOff ] / 2; upline[ gateway[dropOff] ] += upline[ dropOff ] / 2; upline[ dropOff ] = 0; } event Sell( address indexed addr, uint256 bondsSold, uint256 resolves, uint red, uint green, uint blue); function sell(uint amountToSell) public{ address sender = sender; uint bondsBefore = bondContract.balanceOf( address(proxy[sender]) ); uint mintedResolves = proxy[sender].sell(amountToSell); uint _red = redBonds[sender] / bondsBefore; uint _green = greenBonds[sender] / bondsBefore; uint _blue = blueBonds[sender] / bondsBefore; resolvesAddColor(sender, mintedResolves, _red, _green, _blue); votesFor[ votingFor[sender] ] += mintedResolves; _totalSupply += mintedResolves; emit Sell(sender, amountToSell, mintedResolves, _red, _green, _blue ); bondsThinColor(msg.sender, bondsBefore - amountToSell, bondsBefore); pushMinecart(); } function stake(uint amountToStake) public{ address sender = msg.sender; proxy[sender].stake( amountToStake ); colorShift(sender, address(bondContract), amountToStake ); pushMinecart(); } function unstake(uint amountToUnstake) public{ address sender = msg.sender; proxy[sender].unstake( amountToUnstake ); colorShift(address(bondContract), sender, amountToUnstake ); pushMinecart(); } function reinvest() public{ address sender = msg.sender; address proxyAddr = address( proxy[sender] ); uint bal = bondContract.balanceOf( proxyAddr ); uint red = redBonds[sender] / bal; uint green = greenBonds[sender] / bal; uint blue = blueBonds[sender] / bal; uint createdBonds; uint dissolvedResolves; (createdBonds, dissolvedResolves) = proxy[sender].reinvest(); createdBonds += buy( pocket[sender], red, green, blue, false); pocket[sender] = 0; bondsAddColor(sender, createdBonds, red, green, blue); // update core contract's Resolve color address pyrAddr = address(bondContract); uint currentResolves = resolveContract.balanceOf( pyrAddr ); resolvesThinColor(pyrAddr, currentResolves, currentResolves + dissolvedResolves); pushMinecart(); } function withdraw() public{ address payable sender = msg.sender; uint dissolvedResolves = proxy[sender].withdraw(); uint earned = pocket[sender]; pocket[sender] = 0; sender.transfer( earned ); // update core contract's Resolve color address pyrAddr = address(bondContract); uint currentResolves = resolveContract.balanceOf( pyrAddr ); resolvesThinColor(pyrAddr, currentResolves, currentResolves + dissolvedResolves); pushMinecart(); } function proxyAddress(address addr) public view returns(address addressOfProxxy){ return address( proxy[addr] ); } function getProxyOwner(address proxyAddr) public view returns(address ownerAddress){ return proxyOwner[proxyAddr]; } function unbindResolves(uint amount) public { address sender = msg.sender; uint totalResolves = resolveContract.balanceOf( proxyAddress(sender) ); resolvesThinColor( sender, totalResolves - amount, totalResolves); proxy[sender].transfer(sender, amount); } function setVotingFor(address candidate) public { address sender = msg.sender; //Contracts can't vote for anyone. Because then people would just evenly split the pool fund most of the time require( !isContract(sender) );//This could be enhanced, but this is a barebones demonstration of the powhr of resolve tokens uint voteWeight = balanceOf(sender); votesFor[ votingFor[ sender ] ] -= voteWeight; votingFor[ sender ] = candidate; votesFor[ candidate ] += voteWeight; } function assertNewCommunityResolve(address candidate) public { if( votesFor[candidate] > votesFor[communityResolve] ){ communityResolve = candidate; } } function GET_FUNDED() public{ if(msg.sender == communityResolve){ uint money_gotten = pocket[ THIS ]; pocket[ THIS ] = 0; msg.sender.transfer(money_gotten); pushMinecart(); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes memory _data) public returns (bool success) { if( balanceOf(msg.sender) < _value ) revert(); if( isContract(_to) ){ return transferToContract(_to, _value, _data); }else{ return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)){ return transferToContract(_to, _value, empty); }else{ return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) public view returns (bool is_contract) { uint length = 0; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; }else { return false; } } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes memory _data) private returns (bool success) { moveTokens(msg.sender,_to,_value); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes memory _data) private returns (bool success) { moveTokens(msg.sender,_to,_value); ERC223ReceivingContract reciever = ERC223ReceivingContract(_to); reciever.tokenFallback(msg.sender, _value, _data); return true; } function moveTokens(address _from, address _to, uint _amount) internal{ colorShift(_from, _to, _amount); ensureProxy(_to); votesFor[ votingFor[_from] ] -= _amount; votesFor[ votingFor[_to] ] += _amount; proxy[_from].transfer( address(proxy[_to]), _amount ); } function RGB_ratio(uint r, uint g, uint b, uint numerator, uint denominator) internal pure returns(uint,uint,uint){ return (r * numerator / denominator, g * numerator / denominator, b * numerator / denominator ); } function colorShift(address _from, address _to, uint _amount) internal{ //uint bal = proxy[_from].getBalance(); /*uint red_ratio = redResolves[_from] * _amount / bal; uint green_ratio = greenResolves[_from] * _amount / bal; uint blue_ratio = blueResolves[_from] * _amount / bal;*/ (uint red_ratio, uint green_ratio, uint blue_ratio) = RGB_ratio(redResolves[_from], greenResolves[_from], blueResolves[_from], _amount, proxy[_from].getBalance() ); redResolves[_from] -= red_ratio; greenResolves[_from] -= green_ratio; blueResolves[_from] -= blue_ratio; redResolves[_to] += red_ratio; greenResolves[_to] += green_ratio; blueResolves[_to] += blue_ratio; } function allowance(address src, address guy) public view returns (uint) { return approvals[src][guy]; } function transferFrom(address src, address dst, uint wad) public returns (bool){ address sender = msg.sender; require(approvals[src][sender] >= wad); require(proxy[src].getBalance() >= wad); if (src != sender) { approvals[src][sender] -= wad; } moveTokens(src,dst,wad); return true; } event Approval(address indexed src, address indexed guy, uint wad); address sender = msg.sender; function approve(address guy, uint wad) public returns (bool) { approvals[sender][guy] = wad; emit Approval(sender, guy, wad); return true; } function resolvesAddColor(address addr, uint amount , uint red, uint green, uint blue) internal{ redResolves[addr] += red * amount; greenResolves[addr] += green * amount; blueResolves[addr] += blue * amount; } function bondsAddColor(address addr, uint amount , uint red, uint green, uint blue) internal{ redBonds[addr] += red * amount; greenBonds[addr] += green * amount; blueBonds[addr] += blue * amount; } function resolvesThinColor(address addr, uint newWeight, uint oldWeight) internal{ redResolves[addr] = redResolves[addr] * newWeight / oldWeight; greenResolves[addr] = greenResolves[addr] * newWeight / oldWeight; blueResolves[addr] = blueResolves[addr] * newWeight / oldWeight; } function bondsThinColor(address addr, uint newWeight, uint oldWeight) internal{ redBonds[addr] = redBonds[addr] * newWeight / oldWeight; greenBonds[addr] = greenBonds[addr] * newWeight / oldWeight; blueBonds[addr] = blueBonds[addr] * newWeight / oldWeight; } function () payable external { if (msg.value > 0) { uint totalHoldings = bondContract.balanceOf( address(proxy[msg.sender]) ); uint _red = redBonds[msg.sender]/totalHoldings; uint _green = greenBonds[msg.sender]/totalHoldings; uint _blue = blueBonds[msg.sender]/totalHoldings; buy(_red, _green, _blue); } else { //withdraw(); } } } contract BondContract{ function balanceOf(address _owner) public view returns (uint256 balance); function sellBonds(uint amount) public returns(uint,uint); function getResolveContract() public view returns(address); function pullResolves(uint amount) external; function reinvestEarnings(uint amountFromEarnings) public returns(uint,uint); function withdraw(uint amount) public returns(uint); function fund() payable public returns(uint); function resolveEarnings(address _owner) public view returns (uint256 amount); } contract ResolveContract{ function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint _value) public returns (bool success); } contract PyramidProxy{ ColorToken router; BondContract public bondContract; ResolveContract public resolveContract; uint ETH; address THIS = address(this); constructor(ColorToken _router, BondContract _BondContract) public{ router = _router; bondContract = _BondContract; resolveContract = ResolveContract( _BondContract.getResolveContract() ); } modifier routerOnly{ require(msg.sender == address(router)); _; } function sell(uint amount) public view routerOnly() returns (uint){ return 1; } function stake(uint amount) public routerOnly(){ } function transfer(address addr, uint amount) public routerOnly(){ } function () payable external routerOnly(){ ETH += msg.value; } function buy() public routerOnly() returns(uint){ uint _ETH = ETH; ETH = 0; return bondContract.fund.value( _ETH )(); } function cash2Owner() internal{ address payable owner = address(uint160( router.getProxyOwner( THIS ) ) ); uint _ETH = ETH; ETH = 0; owner.transfer( _ETH ); } function getBalance() public view returns (uint balance) { address bC = address(bondContract); if( THIS == bC ){ return resolveContract.balanceOf( bC ); }else{ return resolveContract.balanceOf( THIS ); } } function resolveEarnings() internal view returns(uint){ return bondContract.resolveEarnings( THIS ); } function reinvest() public routerOnly() returns(uint,uint){ return bondContract.reinvestEarnings( resolveEarnings() ); } function withdraw() public routerOnly() returns(uint){ uint dissolvedResolves = bondContract.withdraw( resolveEarnings() ); cash2Owner(); return dissolvedResolves; } /*function sell(uint amount) public routerOnly() returns (uint){ uint resolves; (,resolves) = bondContract.sellBonds(amount); cash2Owner(); return resolves; } function stake(uint amount) public routerOnly(){ resolveContract.transfer( address(bondContract), amount ); } function transfer(address addr, uint amount) public routerOnly(){ resolveContract.transfer( addr, amount ); }*/ function unstake(uint amount) public routerOnly(){ bondContract.pullResolves( amount ); } } contract ERC223ReceivingContract{ function tokenFallback(address _from, uint _value, bytes calldata _data) external; }
Contracts can't vote for anyone. Because then people would just evenly split the pool fund most of the time
function setVotingFor(address candidate) public { address sender = msg.sender; uint voteWeight = balanceOf(sender); votesFor[ votingFor[ sender ] ] -= voteWeight; votingFor[ sender ] = candidate; votesFor[ candidate ] += voteWeight; }
7,240,915
./partial_match/1/0xa48F7A48BDAFf54587A1C4e4B2f35459a2328E29/sources/BattleFish.sol
===================== ===================== ===== ===== ===== Staking ===== ===== ===== ===================== =====================/
function stakedBalanceOf(address account) external view override returns (uint256) { return _stakedBalances[account]; }
9,244,433
pragma solidity ^0.4.18; /** * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool); /** * @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); } /** * @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); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /*^ ^*/ } /* k to the N to the 0 | () (..) () \ .' kn0 thy token v 1.0 | __ rbl __ } .',,,,,,,,,,,,,,,,,,_____|_(\\\-----\\*/ contract kn0Token is StandardToken { string public name; // solium-disable-line uppercase string public symbol; // solium-disable-line uppercase uint8 public decimals; // solium-disable-line uppercase uint256 public aDropedThisWeek; uint256 lastWeek; uint256 decimate; uint256 weekly_limit; uint256 air_drop; mapping(address => uint256) airdroped; 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)); require(newOwner != address(this)); OwnershipTransferred(owner, newOwner); owner = newOwner; update(); } /** * @dev kn0more */ function destroy() onlyOwner external { selfdestruct(owner); } function kn0Token(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) public { // 0xebbebae0fe balances[msg.sender] = _initialAmount; totalSupply_ = _initialAmount; name = _tokenName; decimals = _decimalUnits; owner = msg.sender; symbol = _tokenSymbol; Transfer(0x0, msg.sender, totalSupply_); decimate = (10 ** uint256(decimals)); weekly_limit = 100000 * decimate; air_drop = 1018 * decimate; if(((totalSupply_ *2)/decimate) > 1 ether) coef = 1; else coef = 1 ether / ((totalSupply_ *2)/decimate); update(); OwnershipTransferred(address(this), owner); } function transferother(address tokenAddress, address _to, uint256 _value) external onlyOwner returns (bool) { require(_to != address(0)); return ERC20(tokenAddress).transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); update(); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // if no balance, see if eligible for airdrop instead if(balances[msg.sender] == 0) { uint256 qty = availableAirdrop(msg.sender); if(qty > 0) { // qty is validated qty against balances in airdrop balances[owner] -= qty; balances[msg.sender] += qty; Transfer(owner, _to, _value); update(); airdroped[msg.sender] = qty; aDropedThisWeek += qty; // airdrops don't trigger ownership change return true; } revert(); // no go } // existing balance if(balances[msg.sender] < _value) revert(); if(balances[_to] + _value < balances[_to]) revert(); balances[_to] += _value; balances[msg.sender] -= _value; Transfer(msg.sender, _to, _value); update(); return true; } function balanceOf(address who) public view returns (uint256 balance) { balance = balances[who]; if(balance == 0) return availableAirdrop(who); return balance; } /* * @dev check the faucet */ function availableAirdrop(address who) internal constant returns (uint256) { if(balances[owner] == 0) return 0; if(airdroped[who] > 0) return 0; // already used airdrop if (thisweek() > lastWeek || aDropedThisWeek < weekly_limit) { if(balances[owner] > air_drop) return air_drop; else return balances[owner]; } return 0; } function thisweek() private view returns (uint256) { return now / 1 weeks; } function getAirDropedToday() public view returns (uint256) { if (thisweek() > lastWeek) return 0; else return aDropedThisWeek; } function transferTo(address _to) external onlyOwner { require(_to != address(0)); assert(_to.send(this.balance)); } function () payable public { uint256 qty = calc(msg.value); if(qty > 0) { balances[msg.sender] += qty; balances[owner] -= qty; Transfer(owner, msg.sender, qty); update(); } else revert(); } uint256 public current; uint256 public coef; uint256 public ownerBalance; function update() internal { if(balances[owner] != ownerBalance) { current = (((totalSupply_ - balances[owner]) ** 2) / coef); ownerBalance = balances[owner]; } } function calc(uint256 value) public view returns (uint256) { if(balances[owner] == 0) return 0; uint256 x = (coef * (value + current)); uint256 qty = x; uint256 z = (x + 1) / 2; while (z < qty) { qty = z; z = (x / z + z) / 2; } uint256 worth = (qty - (totalSupply_ - balances[owner])); if(worth > balances[owner]) return balances[owner]; return worth; } }
check the faucet/
function availableAirdrop(address who) internal constant returns (uint256) { if(balances[owner] == 0) return 0; if (thisweek() > lastWeek || aDropedThisWeek < weekly_limit) { if(balances[owner] > air_drop) return air_drop; else return balances[owner]; } return 0; }
14,121,158
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; pragma abicoder v2; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; } /** * @title UZPreSaleVesting * @author Unizen * @notice Presale distribution contract, that also allows claiming * all of the rewards of the whole quarter, as holder tokens. These can be * swapped 1 : 1 for an already vested amount of the final reward token. * This is relevant, since holder tokens can be staked, just as the real token * so the early investors don't lose out on an important benefit. **/ contract UZPreSaleVesting is Initializable, OwnableUpgradeable, PausableUpgradeable { using SafeERC20 for IERC20; using SafeERC20 for IERC20Burnable; using SafeMath for uint256; struct UserData { // users total utility tokens uint256 totalRewards; // used to store pending rewards // if a date needs to be adjusted uint256 savedRewards; // already claimed rewards uint256 claimedRewards; // tranches of holder tokens claimed uint8 claimedTranches; } // user data for stakers mapping(address => UserData) public _userData; // the actual token, that will be vested IERC20 public utilityToken; // the non transferable holder token IERC20Burnable public holderToken; // blockHeights of the distributions tranches uint256[] public _tranches; // amount of blocks per tranche uint256 public _trancheDuration; // safety guard in case somethings goes wrong // the contract can be halted bool internal _locked; function initialize( uint256 startBlock, uint256 duration, address rewardToken, address swapToken ) public virtual initializer { __Ownable_init(); __Pausable_init(); utilityToken = IERC20(rewardToken); holderToken = IERC20Burnable(swapToken); _calculateTranches(startBlock, duration); // 1 tranches _locked = false; } /* view functions */ /** * @dev Returns current vested amount of utility tokens * @return pendingRewards amount of accrued / swappable utility tokens **/ function getPendingUtilityTokens() external view returns (uint256 pendingRewards) { pendingRewards = _getPendingUtilityTokens(_msgSender()); } /** * @dev Returns the amount of accrued holder tokens for the current user * @return pendingHolderTokens amount of accrued / claimable holder tokens * @return tranches amount of claimable trances (max 3) **/ function getPendingHolderTokens() public view returns (uint256 pendingHolderTokens, uint8 tranches) { // return 0 if tranches are not set or first tranche is still in the future if (_tranches[0] == 0 || _tranches[0] >= block.number) return (0, 0); // fetch users data UserData storage user = _userData[_msgSender()]; // if user has no rewards assigned, return 0 if (_userData[_msgSender()].totalRewards == 0) return (0, 0); // calculate the amount of holder tokens per tranche uint256 trancheAmount = user.totalRewards.div(_tranches.length); // check every tranch if it can be claimed for (uint256 i = 0; i < _tranches.length; i++) { // tranches start block needs to be in the bast and needs to be unclaimed if (block.number > _tranches[i] && user.claimedTranches <= i) { // increase the amount of pending holder tokens pendingHolderTokens = pendingHolderTokens.add(trancheAmount); // increase the amount of pending tranches tranches++; } } } /** * @dev Helper function to check if a user is eligible for pre sale vesting * @param user address to check for eligibility * @return bool returns true if eligible **/ function isUserEligible(address user) external view returns (bool) { return (_userData[user].totalRewards > 0); } /** * @dev Convenience function to check the block number for the next tranche * @return tranche block.number of the start of this tranche. 0 if finished **/ function getNextHolderTokenTranche() external view returns (uint256 tranche) { for (uint256 i = 0; i < _tranches.length; i++) { if (block.number < _tranches[i]) return _tranches[i]; } return 0; } /** * @dev Returns whether the contract is currently locked * @return bool Return value is true, if the contract is locked **/ function getLocked() public view returns (bool) { return _locked; } /* mutating functions */ /** * @dev Claim all pending holder tokens for the requesting user **/ function claimHolderTokens() external whenNotPaused notLocked { require(_userData[msg.sender].totalRewards > 0, "NOT_WHITELISTED"); // fetch pending holder tokens (uint256 pendingRewards, uint8 tranches) = getPendingHolderTokens(); // return if none exist require(pendingRewards > 0, "NO_PENDING_REWARDS"); // check that the contract has sufficient holder tokens to send require( holderToken.balanceOf(address(this)) >= pendingRewards, "EXCEEDS_AVAIL_HT" ); // update user data with the amount of claimed tranches _userData[_msgSender()].claimedTranches = _userData[_msgSender()].claimedTranches + tranches; // sent holder tokens to user holderToken.safeTransfer(_msgSender(), pendingRewards); } /** * @dev Swaps desired `amount` of holder tokens to utility tokens. The amount * cannot exceed the users current pending / accrued utility tokens. * Holder tokens will be burned in the process and swap is always 1:1 * @param amount Amount of holder tokens to be swapped to utility tokens */ function swapHolderTokensForUtility(uint256 amount) external whenNotPaused notLocked { require(_userData[msg.sender].totalRewards > 0, "NOT_WHITELISTED"); // fetch pending utility tokens uint256 pendingRewards = _getPendingUtilityTokens(_msgSender()); // return if no utility tokens are ready to be vested require(pendingRewards > 0, "NO_PENDING_REWARDS"); // currently vested utility tokens are the maximum to be swapped // return if the desired amount exceeds the currently vested utility tokens require(pendingRewards >= amount, "AMOUNT_EXCEEDS_REWARDS"); // check that the contract has sufficient utility tokens to send require( utilityToken.balanceOf(address(this)) >= amount, "EXCEEDS_AVAILABLE_TOKENS" ); // update users claimed amount of utility tokens. these will be removed from the // pending tokens _userData[_msgSender()].claimedRewards = _userData[_msgSender()] .claimedRewards .add(amount); // transfer holder tokens from user to contract holderToken.safeTransferFrom(_msgSender(), address(this), amount); // burn holder tokens holderToken.burn(amount); // send same amount of utility tokens to user utilityToken.safeTransfer(_msgSender(), amount); } /* internal functions */ /** * @dev This function will calculate the start blocks for each tranche * @param startBlock start of the vesting contract * @param duration Amount of blocks per tranche*/ function _calculateTranches(uint256 startBlock, uint256 duration) internal { // start block cannot be 0 require(startBlock > 0, "NO_START_BLOCK"); // duration of tranches needs to be bigger than 0 require(duration > 0, "NO_DURATION"); // set tranche duration _trancheDuration = duration; // tranche 1 starts at start _tranches.push(startBlock); // 1tranches only } /** * @dev The actual internal function that is used to calculate the accrued * utility tokens, ready for vesting of a user * @param user the address to check for pending utility tokens * @return pendingRewards amount of accrued utility tokens up to the current block **/ function _getPendingUtilityTokens(address user) internal view returns (uint256 pendingRewards) { // return 0 if tranches are not set or first tranche is still in the future if (_tranches[0] == 0 || _tranches[0] >= block.number) return 0; // fetch users data UserData storage userData = _userData[user]; // if user has no rewards assigned, return 0 if (userData.totalRewards == 0) return 0; // calculate the multiplier, used to calculate the accrued utility tokens // from start of vesting to current block uint256 multiplier = block.number.sub(_tranches[0]); // calculate the maximal multiplier, to be used as threshold, so we // don't calculate more rewards, after vesting end reached uint256 maxDuration = _trancheDuration.mul(_tranches.length); // use multiplier if it no exceeds maximum. otherwise use max multiplier multiplier = (multiplier <= maxDuration) ? multiplier : maxDuration; // calculate the users pending / accrued utility tokens // based on users rewards per block and the given multiplier. // remove already claimed rewards by swapping holder tokens // for utility tokens uint256 rewardsPerBlock = userData.totalRewards.div(maxDuration); uint256 totalReward = multiplier.mul(rewardsPerBlock).add( userData.savedRewards ); pendingRewards = totalReward.sub(userData.claimedRewards); } /* control functions */ /** * @dev Convenience function to add a list of users to be eligible for vesting * @param users list of addresses for eligible users * @param rewards list of total rewards for the users **/ function addMultipleUserVestings( address[] calldata users, uint256[] calldata rewards ) external onlyOwner { // check that user array is not empty require(users.length > 0, "NO_USERS"); // check that rewards array is not empty require(rewards.length > 0, "NO_VESTING_DATA"); // check that user and reward array a equal length require(users.length == rewards.length, "PARAM_NOT_EQ_LENGTH"); // loop through the list and call the default function to add new vestings for (uint8 i = 0; i < users.length; i++) { addUserVesting(users[i], rewards[i]); } } /** * @dev Adds a new user eligible for vesting. Automatically calculates rewardsPerBlock, * based on the tranches and tranche duration * @param user address of eligible user * @param totalRewards amount of rewards to be vested for this user **/ function addUserVesting(address user, uint256 totalRewards) public onlyOwner { // check that address is not empty require(user != address(0), "ZERO_ADDRESS"); // check that user has rewards to receive require(totalRewards > 0, "NO_REWARDS"); // check that user does not exist yet require(_userData[user].totalRewards == 0, "EXISTING_USER"); // start block is start of tranche one uint256 startBlock = _tranches[0]; // end block is tranche three + tranche duration uint256 endBlock = _tranches[_tranches.length - 1].add( _trancheDuration ); // check that current block is still below end of vesting // require(block.number < endBlock, "VESTING_FINISHED"); // make sure that start block is smaller than end block // require(endBlock > startBlock, "INVALID_START_BLOCK"); // create user data object UserData memory newUserData; newUserData.totalRewards = totalRewards; _userData[user] = newUserData; } /** * @dev should allow contract's owner add more tranches * @param _tranchesAmount amount of tranches want to add: 1, 2, 3 ... */ function addTranches(uint256 _tranchesAmount) external onlyOwner { uint256 lastTranches = _tranches[_tranches.length - 1]; for (uint256 i = 0; i < _tranchesAmount; i++) { _tranches.push(lastTranches.add(_trancheDuration)); lastTranches = _tranches[_tranches.length - 1]; } } /** * @dev pause smart contract */ function pause() public onlyOwner { _pause(); } /** * @dev unpause smart contract */ function unPause() public onlyOwner { _unpause(); } function emergencyWithDrawToken(address token, address to) external whenPaused onlyOwner { uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(to, balance); } /** * @dev Remove eligibility of a user. Either deactivate completely or optionally leave the already * accrued utility tokens up for claiming, but do not accrue any further tokens. * @param user Address of the user to remove * @param keepVestedTokens If true, the user will still be able to claim / swap already accrued token rewards. But won't accrue more. **/ function removeUserVesting(address user, bool keepVestedTokens) external onlyOwner { // check that user address is not empty require(user != address(0), "ADDRESS_ZERO"); // check that user is existing and currently eligible require(_userData[user].totalRewards > 0, "INVALID_USER"); // fetch user data UserData storage userData = _userData[user]; // store users pending / accrued rewards, if `keepVestedTokens` is true. Otherwise set to zero userData.savedRewards = (keepVestedTokens == true) ? userData.savedRewards.add(_getPendingUtilityTokens(user)) : 0; // set users total rewards to users saved rewards, if `keepVestedTokens` is true. Otherwise set to zero userData.totalRewards = (keepVestedTokens == true) ? userData.savedRewards.add(userData.claimedRewards) : 0; } function setLocked(bool locked) external onlyOwner { require(locked != _locked, "SAME_VALUE"); _locked = locked; } function setDuration(uint256 _newDuration) external onlyOwner { _trancheDuration = _newDuration; } /* modifiers */ modifier notLocked() { require(_locked == false, "LOCKED"); _; } } // 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 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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 "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; }
internal functions / This function will calculate the start blocks for each tranche startBlock start of the vesting contract duration Amount of blocks per tranche/ start block cannot be 0 duration of tranches needs to be bigger than 0 set tranche duration tranche 1 starts at start
function _calculateTranches(uint256 startBlock, uint256 duration) internal { require(startBlock > 0, "NO_START_BLOCK"); require(duration > 0, "NO_DURATION"); _trancheDuration = duration; }
355,108
./full_match/3/0x4d7005e236C6992F9DE8df5b4EAA6C69F705d62E/sources/browser/NewUdonMasterChef.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accUdonsPerShare: 0 })); }
8,115,854
pragma solidity ^0.5.10; /** * @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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: contracts/commons/Ownable.sol pragma solidity ^0.5.10; contract Ownable { address public owner; event TransferOwnership(address _from, address _to); constructor() public { owner = msg.sender; emit TransferOwnership(address(0), msg.sender); } modifier onlyOwner() { require(msg.sender == owner, "only owner"); _; } function setOwner(address _owner) external onlyOwner { emit TransferOwnership(owner, _owner); owner = _owner; } } // File: contracts/commons/StorageUnit.sol pragma solidity ^0.5.10; contract StorageUnit { address private owner; mapping(bytes32 => bytes32) private store; constructor() public { owner = msg.sender; } function write(bytes32 _key, bytes32 _value) external { /* solium-disable-next-line */ require(msg.sender == owner); store[_key] = _value; } function read(bytes32 _key) external view returns (bytes32) { return store[_key]; } } // File: contracts/utils/IsContract.sol pragma solidity ^0.5.10; library IsContract { function isContract(address _addr) internal view returns (bool) { bytes32 codehash; /* solium-disable-next-line */ assembly { codehash := extcodehash(_addr) } return codehash != bytes32(0) && codehash != bytes32(0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } } // File: contracts/utils/DistributedStorage.sol pragma solidity ^0.5.10; library DistributedStorage { function contractSlot(bytes32 _struct) private view returns (address) { return address( uint256( keccak256( abi.encodePacked( byte(0xff), address(this), _struct, keccak256(type(StorageUnit).creationCode) ) ) ) ); } function deploy(bytes32 _struct) private { bytes memory slotcode = type(StorageUnit).creationCode; /* solium-disable-next-line */ assembly{ pop(create2(0, add(slotcode, 0x20), mload(slotcode), _struct)) } } function write( bytes32 _struct, bytes32 _key, bytes32 _value ) internal { StorageUnit store = StorageUnit(contractSlot(_struct)); if (!IsContract.isContract(address(store))) { deploy(_struct); } /* solium-disable-next-line */ (bool success, ) = address(store).call( abi.encodeWithSelector( store.write.selector, _key, _value ) ); require(success, "error writing storage"); } function read( bytes32 _struct, bytes32 _key ) internal view returns (bytes32) { StorageUnit store = StorageUnit(contractSlot(_struct)); if (!IsContract.isContract(address(store))) { return bytes32(0); } /* solium-disable-next-line */ (bool success, bytes memory data) = address(store).staticcall( abi.encodeWithSelector( store.read.selector, _key ) ); require(success, "error reading storage"); return abi.decode(data, (bytes32)); } } // File: contracts/utils/SafeMath.sol pragma solidity ^0.5.10; library SafeMath { function add(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; require(z >= x, "Add overflow"); return z; } function sub(uint256 x, uint256 y) internal pure returns (uint256) { require(x >= y, "Sub underflow"); return x - y; } function mult(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; require(z / x == y, "Mult overflow"); return z; } function div(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); return x / y; } function divRound(uint256 x, uint256 y) internal pure returns (uint256) { require(y != 0, "Div by zero"); uint256 r = x / y; if (x % y != 0) { r = r + 1; } return r; } } // File: contracts/utils/Math.sol pragma solidity ^0.5.10; library Math { function orderOfMagnitude(uint256 input) internal pure returns (uint256){ uint256 counter = uint(-1); uint256 temp = input; do { temp /= 10; counter++; } while (temp != 0); return counter; } 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; } } } // File: contracts/utils/GasPump.sol pragma solidity ^0.5.10; contract GasPump { bytes32 private stub; modifier requestGas(uint256 _factor) { if (tx.gasprice == 0 || gasleft() > block.gaslimit) { uint256 startgas = gasleft(); _; uint256 delta = startgas - gasleft(); uint256 target = (delta * _factor) / 100; startgas = gasleft(); while (startgas - gasleft() < target) { // Burn gas stub = keccak256(abi.encodePacked(stub)); } } else { _; } } } // File: contracts/interfaces/IERC20.sol pragma solidity ^0.5.10; 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, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function approve(address _spender, uint256 _value) external returns (bool success); function balanceOf(address _owner) external view returns (uint256 balance); } // File: contracts/commons/AddressMinHeap.sol pragma solidity ^0.5.10; /* @author Agustin Aguilar <[email protected]> */ library AddressMinHeap { using AddressMinHeap for AddressMinHeap.Heap; struct Heap { uint256[] entries; mapping(address => uint256) index; } function initialize(Heap storage _heap) internal { require(_heap.entries.length == 0, "already initialized"); _heap.entries.push(0); } function encode(address _addr, uint256 _value) internal pure returns (uint256 _entry) { /* solium-disable-next-line */ assembly { _entry := not(or(and(0xffffffffffffffffffffffffffffffffffffffff, _addr), shl(160, _value))) } } function decode(uint256 _entry) internal pure returns (address _addr, uint256 _value) { /* solium-disable-next-line */ assembly { let entry := not(_entry) _addr := and(entry, 0xffffffffffffffffffffffffffffffffffffffff) _value := shr(160, entry) } } function decodeAddress(uint256 _entry) internal pure returns (address _addr) { /* solium-disable-next-line */ assembly { _addr := and(not(_entry), 0xffffffffffffffffffffffffffffffffffffffff) } } function top(Heap storage _heap) internal view returns(address, uint256) { if (_heap.entries.length < 2) { return (address(0), 0); } return decode(_heap.entries[1]); } function has(Heap storage _heap, address _addr) internal view returns (bool) { return _heap.index[_addr] != 0; } function size(Heap storage _heap) internal view returns (uint256) { return _heap.entries.length - 1; } function entry(Heap storage _heap, uint256 _i) internal view returns (address, uint256) { return decode(_heap.entries[_i + 1]); } // RemoveMax pops off the root element of the heap (the highest value here) and rebalances the heap function popTop(Heap storage _heap) internal returns(address _addr, uint256 _value) { // Ensure the heap exists uint256 heapLength = _heap.entries.length; require(heapLength > 1, "The heap does not exists"); // take the root value of the heap (_addr, _value) = decode(_heap.entries[1]); _heap.index[_addr] = 0; if (heapLength == 2) { _heap.entries.length = 1; } else { // Takes the last element of the array and put it at the root uint256 val = _heap.entries[heapLength - 1]; _heap.entries[1] = val; // Delete the last element from the array _heap.entries.length = heapLength - 1; // Start at the top uint256 ind = 1; // Bubble down ind = _heap.bubbleDown(ind, val); // Update index _heap.index[decodeAddress(val)] = ind; } } // Inserts adds in a value to our heap. function insert(Heap storage _heap, address _addr, uint256 _value) internal { require(_heap.index[_addr] == 0, "The entry already exists"); // Add the value to the end of our array uint256 encoded = encode(_addr, _value); _heap.entries.push(encoded); // Start at the end of the array uint256 currentIndex = _heap.entries.length - 1; // Bubble Up currentIndex = _heap.bubbleUp(currentIndex, encoded); // Update index _heap.index[_addr] = currentIndex; } function update(Heap storage _heap, address _addr, uint256 _value) internal { uint256 ind = _heap.index[_addr]; require(ind != 0, "The entry does not exists"); uint256 can = encode(_addr, _value); uint256 val = _heap.entries[ind]; uint256 newInd; if (can < val) { // Bubble down newInd = _heap.bubbleDown(ind, can); } else if (can > val) { // Bubble up newInd = _heap.bubbleUp(ind, can); } else { // no changes needed return; } // Update entry _heap.entries[newInd] = can; // Update index if (newInd != ind) { _heap.index[_addr] = newInd; } } function bubbleUp(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) { // Bubble up ind = _ind; if (ind != 1) { uint256 parent = _heap.entries[ind / 2]; while (parent < _val) { // If the parent value is lower than our current value, we swap them (_heap.entries[ind / 2], _heap.entries[ind]) = (_val, parent); // Update moved Index _heap.index[decodeAddress(parent)] = ind; // change our current Index to go up to the parent ind = ind / 2; if (ind == 1) { break; } // Update parent parent = _heap.entries[ind / 2]; } } } function bubbleDown(Heap storage _heap, uint256 _ind, uint256 _val) internal returns (uint256 ind) { // Bubble down ind = _ind; uint256 lenght = _heap.entries.length; uint256 target = lenght - 1; while (ind * 2 < lenght) { // get the current index of the children uint256 j = ind * 2; // left child value uint256 leftChild = _heap.entries[j]; // Store the value of the child uint256 childValue; if (target > j) { // The parent has two childs 👨‍👧‍👦 // Load right child value uint256 rightChild = _heap.entries[j + 1]; // Compare the left and right child. // if the rightChild is greater, then point j to it's index // and save the value if (leftChild < rightChild) { childValue = rightChild; j = j + 1; } else { // The left child is greater childValue = leftChild; } } else { // The parent has a single child 👨‍👦 childValue = leftChild; } // Check if the child has a lower value if (_val > childValue) { break; } // else swap the value (_heap.entries[ind], _heap.entries[j]) = (childValue, _val); // Update moved Index _heap.index[decodeAddress(childValue)] = ind; // and let's keep going down the heap ind = j; } } } // File: contracts/Heap.sol pragma solidity ^0.5.10; contract Heap is Ownable { using AddressMinHeap for AddressMinHeap.Heap; // heap AddressMinHeap.Heap private heap; // Heap events event JoinHeap(address indexed _address, uint256 _balance, uint256 _prevSize); event LeaveHeap(address indexed _address, uint256 _balance, uint256 _prevSize); uint256 public constant TOP_SIZE = 512; constructor() public { heap.initialize(); } function topSize() external pure returns (uint256) { return TOP_SIZE; } function addressAt(uint256 _i) external view returns (address addr) { (addr, ) = heap.entry(_i); } function indexOf(address _addr) external view returns (uint256) { return heap.index[_addr]; } function entry(uint256 _i) external view returns (address, uint256) { return heap.entry(_i); } function top() external view returns (address, uint256) { return heap.top(); } function size() external view returns (uint256) { return heap.size(); } function update(address _addr, uint256 _new) external onlyOwner { uint256 _size = heap.size(); // If the heap is empty // join the _addr if (_size == 0) { emit JoinHeap(_addr, _new, 0); heap.insert(_addr, _new); return; } // Load top value of the heap (, uint256 lastBal) = heap.top(); // If our target address already is in the heap if (heap.has(_addr)) { // Update the target address value heap.update(_addr, _new); // If the new value is 0 // always pop the heap // we updated the heap, so our address should be on top if (_new == 0) { heap.popTop(); emit LeaveHeap(_addr, 0, _size); } } else { // IF heap is full or new balance is higher than pop heap if (_new != 0 && (_size < TOP_SIZE || lastBal < _new)) { // If heap is full pop heap if (_size >= TOP_SIZE) { (address _poped, uint256 _balance) = heap.popTop(); emit LeaveHeap(_poped, _balance, _size); } // Insert new value heap.insert(_addr, _new); emit JoinHeap(_addr, _new, _size); } } } } // File: contracts/ShuffleToken.sol pragma solidity ^0.5.10; contract ShuffleToken is Ownable, GasPump, IERC20 { using DistributedStorage for bytes32; using SafeMath for uint256; // Shuffle events event Winner(address indexed _addr, uint256 _value); // Managment events event SetName(string _prev, string _new); event SetExtraGas(uint256 _prev, uint256 _new); event SetHeap(address _prev, address _new); event WhitelistFrom(address _addr, bool _whitelisted); event WhitelistTo(address _addr, bool _whitelisted); uint256 public totalSupply; bytes32 private constant BALANCE_KEY = keccak256("balance"); // game uint256 public constant FEE = 100; // metadata string public name = "Shuffle.Monster V3"; string public constant symbol = "SHUF"; uint8 public constant decimals = 18; // fee whitelist mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo; // heap Heap public heap; // internal uint256 public extraGas; bool inited; function init( address _to, uint256 _amount ) external { // Only init once assert(!inited); inited = true; // Sanity checks assert(totalSupply == 0); assert(address(heap) == address(0)); // Create Heap heap = new Heap(); emit SetHeap(address(0), address(heap)); // Init contract variables and mint // entire token balance extraGas = 15; emit SetExtraGas(0, extraGas); emit Transfer(address(0), _to, _amount); _setBalance(_to, _amount); totalSupply = _amount; } /// // Storage access functions /// // Getters function _toKey(address a) internal pure returns (bytes32) { return bytes32(uint256(a)); } function _balanceOf(address _addr) internal view returns (uint256) { return uint256(_toKey(_addr).read(BALANCE_KEY)); } function _allowance(address _addr, address _spender) internal view returns (uint256) { return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("allowance", _spender)))); } function _nonce(address _addr, uint256 _cat) internal view returns (uint256) { return uint256(_toKey(_addr).read(keccak256(abi.encodePacked("nonce", _cat)))); } // Setters function _setAllowance(address _addr, address _spender, uint256 _value) internal { _toKey(_addr).write(keccak256(abi.encodePacked("allowance", _spender)), bytes32(_value)); } function _setNonce(address _addr, uint256 _cat, uint256 _value) internal { _toKey(_addr).write(keccak256(abi.encodePacked("nonce", _cat)), bytes32(_value)); } function _setBalance(address _addr, uint256 _balance) internal { _toKey(_addr).write(BALANCE_KEY, bytes32(_balance)); heap.update(_addr, _balance); } /// // Internal methods /// function _isWhitelisted(address _from, address _to) internal view returns (bool) { return whitelistFrom[_from]||whitelistTo[_to]; } function _random(address _s1, uint256 _s2, uint256 _s3, uint256 _max) internal pure returns (uint256) { uint256 rand = uint256(keccak256(abi.encodePacked(_s1, _s2, _s3))); return rand % (_max + 1); } function _pickWinner(address _from, uint256 _value) internal returns (address winner) { // Get order of magnitude of the tx uint256 magnitude = Math.orderOfMagnitude(_value); // Pull nonce for a given order of magnitude uint256 nonce = _nonce(_from, magnitude); _setNonce(_from, magnitude, nonce + 1); // pick entry from heap winner = heap.addressAt(_random(_from, nonce, magnitude, heap.size() - 1)); } function _transferFrom(address _operator, address _from, address _to, uint256 _value, bool _payFee) internal { // If transfer amount is zero // emit event and stop execution if (_value == 0) { emit Transfer(_from, _to, 0); return; } // Load sender balance uint256 balanceFrom = _balanceOf(_from); require(balanceFrom >= _value, "balance not enough"); // Check if operator is sender if (_from != _operator) { // If not, validate allowance uint256 allowanceFrom = _allowance(_from, _operator); // If allowance is not 2 ** 256 - 1, consume allowance if (allowanceFrom != uint(-1)) { // Check allowance and save new one require(allowanceFrom >= _value, "allowance not enough"); _setAllowance(_from, _operator, allowanceFrom.sub(_value)); } } // Calculate receiver balance // initial receive is full value uint256 receive = _value; uint256 burn = 0; uint256 shuf = 0; // Change sender balance _setBalance(_from, balanceFrom.sub(_value)); // If the transaction is not whitelisted // or if sender requested to pay the fee // calculate fees if (_payFee || !_isWhitelisted(_from, _to)) { // Fee is the same for BURN and SHUF // If we are sending value one // give priority to BURN burn = _value.divRound(FEE); shuf = _value == 1 ? 0 : burn; // Subtract fees from receiver amount receive = receive.sub(burn.add(shuf)); // Burn tokens totalSupply = totalSupply.sub(burn); emit Transfer(_from, address(0), burn); // Shuffle tokens // Pick winner pseudo-randomly address winner = _pickWinner(_from, _value); // Transfer balance to winner _setBalance(winner, _balanceOf(winner).add(shuf)); emit Winner(winner, shuf); emit Transfer(_from, winner, shuf); } // Sanity checks // no tokens where created assert(burn.add(shuf).add(receive) == _value); // Add tokens to receiver _setBalance(_to, _balanceOf(_to).add(receive)); emit Transfer(_from, _to, receive); } /// // Managment /// function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistTo(_addr, _whitelisted); whitelistTo[_addr] = _whitelisted; } function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistFrom(_addr, _whitelisted); whitelistFrom[_addr] = _whitelisted; } function setName(string calldata _name) external onlyOwner { emit SetName(name, _name); name = _name; } function setExtraGas(uint256 _gas) external onlyOwner { emit SetExtraGas(extraGas, _gas); extraGas = _gas; } function setHeap(Heap _heap) external onlyOwner { emit SetHeap(address(heap), address(_heap)); heap = _heap; } ///// // Heap methods ///// function topSize() external view returns (uint256) { return heap.topSize(); } function heapSize() external view returns (uint256) { return heap.size(); } function heapEntry(uint256 _i) external view returns (address, uint256) { return heap.entry(_i); } function heapTop() external view returns (address, uint256) { return heap.top(); } function heapIndex(address _addr) external view returns (uint256) { return heap.indexOf(_addr); } function getNonce(address _addr, uint256 _cat) external view returns (uint256) { return _nonce(_addr, _cat); } ///// // ERC20 ///// function balanceOf(address _addr) external view returns (uint256) { return _balanceOf(_addr); } function allowance(address _addr, address _spender) external view returns (uint256) { return _allowance(_addr, _spender); } function approve(address _spender, uint256 _value) external returns (bool) { emit Approval(msg.sender, _spender, _value); _setAllowance(msg.sender, _spender, _value); return true; } function transfer(address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, msg.sender, _to, _value, false); return true; } function transferWithFee(address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, msg.sender, _to, _value, true); return true; } function transferFrom(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, _from, _to, _value, false); return true; } function transferFromWithFee(address _from, address _to, uint256 _value) external requestGas(extraGas) returns (bool) { _transferFrom(msg.sender, _from, _to, _value, true); return true; } } // File: contracts/utils/SigUtils.sol pragma solidity ^0.5.10; library SigUtils { /** @dev Recovers address who signed the message @param _hash operation ethereum signed message hash @param _signature message `hash` signature */ function ecrecover2( bytes32 _hash, bytes memory _signature ) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; /* solium-disable-next-line */ assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := and(mload(add(_signature, 65)), 255) } if (v < 27) { v += 27; } return ecrecover( _hash, v, r, s ); } } // File: contracts/utils/SafeCast.sol pragma solidity ^0.5.10; library SafeCast { function toUint96(uint256 _a) internal pure returns (uint96) { require(_a <= 2 ** 96 - 1, "cast uint96 overflow"); return uint96(_a); } } // File: contracts/Airdrop.sol pragma solidity ^0.5.10; contract Airdrop is Ownable, ReentrancyGuard { using IsContract for address payable; using SafeCast for uint256; using SafeMath for uint256; ShuffleToken public shuffleToken; // Managment uint64 public maxClaimedBy = 0; uint256 public refsCut; mapping(address => uint256) public customMaxClaimedBy; bool public paused; event SetMaxClaimedBy(uint256 _max); event SetCustomMaxClaimedBy(address _address, uint256 _max); event SetSigner(address _signer, bool _active); event SetMigrator(address _migrator, bool _active); event SetFuse(address _fuse, bool _active); event SetPaused(bool _paused); event SetRefsCut(uint256 _prev, uint256 _new); event Claimed(address _by, address _to, address _signer, uint256 _value, uint256 _claimed); event RefClaim(address _ref, uint256 _val); event ClaimedOwner(address _owner, uint256 _tokens); uint256 public constant MINT_AMOUNT = 1000000 * 10 ** 18; uint256 public constant SHUFLE_BY_ETH = 150; uint256 public constant MAX_CLAIM_ETH = 10 ether; mapping(address => bool) public isSigner; mapping(address => bool) public isMigrator; mapping(address => bool) public isFuse; mapping(address => uint256) public claimed; mapping(address => uint256) public numberClaimedBy; constructor(ShuffleToken _token) public { shuffleToken = _token; shuffleToken.init(address(this), MINT_AMOUNT); emit SetMaxClaimedBy(maxClaimedBy); } // /// // Managment // /// modifier notPaused() { require(!paused, "contract is paused"); _; } function setMaxClaimedBy(uint64 _max) external onlyOwner { maxClaimedBy = _max; emit SetMaxClaimedBy(_max); } function setSigner(address _signer, bool _active) external onlyOwner { isSigner[_signer] = _active; emit SetSigner(_signer, _active); } function setMigrator(address _migrator, bool _active) external onlyOwner { isMigrator[_migrator] = _active; emit SetMigrator(_migrator, _active); } function setFuse(address _fuse, bool _active) external onlyOwner { isFuse[_fuse] = _active; emit SetFuse(_fuse, _active); } function setSigners(address[] calldata _signers, bool _active) external onlyOwner { for (uint256 i = 0; i < _signers.length; i++) { address signer = _signers[i]; isSigner[signer] = _active; emit SetSigner(signer, _active); } } function setCustomMaxClaimedBy(address _address, uint256 _max) external onlyOwner { customMaxClaimedBy[_address] = _max; emit SetCustomMaxClaimedBy(_address, _max); } function setRefsCut(uint256 _val) external onlyOwner { emit SetRefsCut(refsCut, _val); refsCut = _val; } function pause() external { require( isFuse[msg.sender] || msg.sender == owner || isMigrator[msg.sender] || isSigner[msg.sender], "not authorized" ); paused = true; emit SetPaused(true); } function start() external onlyOwner { emit SetPaused(false); paused = false; } // /// // Airdrop // /// function _selfBalance() internal view returns (uint256) { return shuffleToken.balanceOf(address(this)); } function checkFallback(address _to) private returns (bool success) { /* solium-disable-next-line */ (success, ) = _to.call.value(1)(""); } function claim( address _to, address _ref, uint256 _val, bytes calldata _sig ) external notPaused nonReentrant { // Load values uint96 val = _val.toUint96(); // Validate signature bytes32 _hash = keccak256(abi.encodePacked(_to, val)); address signer = SigUtils.ecrecover2(_hash, _sig); require(isSigner[signer], "signature not valid"); // Prepare claim amount uint256 balance = _selfBalance(); uint256 claimVal = Math.min( balance, Math.min( val, MAX_CLAIM_ETH ).mult(SHUFLE_BY_ETH) ); // Sanity checks assert(claimVal <= SHUFLE_BY_ETH.mult(val)); assert(claimVal <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH)); assert(claimVal.div(SHUFLE_BY_ETH) <= MAX_CLAIM_ETH); assert( claimVal.div(SHUFLE_BY_ETH) == _val || claimVal.div(SHUFLE_BY_ETH) == MAX_CLAIM_ETH || claimVal == balance ); // Claim, only once require(claimed[_to] == 0, "already claimed"); claimed[_to] = claimVal; // External claim checks if (msg.sender != _to) { // Validate max external claims uint256 _numberClaimedBy = numberClaimedBy[msg.sender].add(1); require(_numberClaimedBy <= Math.max(maxClaimedBy, customMaxClaimedBy[msg.sender]), "max claim reached"); numberClaimedBy[msg.sender] = _numberClaimedBy; // Check if _to address can receive ETH require(checkFallback(_to), "_to address can't receive tokens"); } // Transfer Shuffle token, paying fee shuffleToken.transferWithFee(_to, claimVal); // Emit events emit Claimed(msg.sender, _to, signer, val, claimVal); // Ref links if (refsCut != 0) { // Only valid for self-claims if (msg.sender == _to && _ref != address(0)) { // Calc transfer extra uint256 extra = claimVal.mult(refsCut).div(10000); // Ignore ref fee if Airdrop balance is not enought if (_selfBalance() >= extra) { shuffleToken.transferWithFee(_ref, extra); emit RefClaim(_ref, extra); // Sanity checks assert(extra <= MAX_CLAIM_ETH.mult(SHUFLE_BY_ETH)); assert(extra <= claimVal); assert(extra == (claimVal * refsCut) / 10000); } } } // If contract is empty, perform self destruct if (balance == claimVal && _selfBalance() == 0) { selfdestruct(address(uint256(owner))); } } // Migration methods event Migrated(address _addr, uint256 _balance); mapping(address => uint256) public migrated; function migrate(address _addr, uint256 _balance, uint256 _require) external notPaused { // Check if migrator is a migrator require(isMigrator[msg.sender], "only migrator can migrate"); // Check if expected migrated matches current migrated require(migrated[_addr] == _require, "_require prev migrate failed"); // Save migrated amount migrated[_addr] = migrated[_addr].add(_balance); // Transfer tokens and emit event shuffleToken.transfer(_addr, _balance); emit Migrated(_addr, _balance); } function fund() external payable { } }
Bubble down Bubble up no changes needed Update index
function update(Heap storage _heap, address _addr, uint256 _value) internal { uint256 ind = _heap.index[_addr]; require(ind != 0, "The entry does not exists"); uint256 can = encode(_addr, _value); uint256 val = _heap.entries[ind]; uint256 newInd; if (can < val) { newInd = _heap.bubbleDown(ind, can); newInd = _heap.bubbleUp(ind, can); return; } if (newInd != ind) { _heap.index[_addr] = newInd; } }
881,557
./partial_match/1/0xe3023a720d6f4d03b78763EDB3587f123565Cc6D/sources/IUCNcoinPresale.sol
@Param to get live price,1. ETH, 2. Btc, 3. BNB, 4. Usdt, 5.Usdc
function getLatestPrice(uint _pid) public view returns (int) { int price; if(_pid == 1) (,price,,,) = EthFeed.latestRoundData(); if(_pid == 2) (,price,,,) = BtcFeed.latestRoundData(); if(_pid == 3) (,price,,,) = BnbFeed.latestRoundData(); if(_pid == 4) (,price,,,) = UsdtFeed.latestRoundData(); if(_pid == 5) (,price,,,) = UsdcFeed.latestRoundData(); return price; }
3,710,723
/** *Submitted for verification at Etherscan.io on 2021-08-11 */ // Dependency file: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: contracts/interfaces/IFarmFactory.sol // pragma solidity ^0.6.10; interface IFarmFactory { function registerFarm (address _farmAddress) external; function userEnteredFarm (address _user) external; function userLeftFarm (address _user) external; } // Dependency file: contracts/farm/Farm.sol // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { IFarmFactory } from "contracts/interfaces/IFarmFactory.sol"; contract Farm is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ============ Struct ============ */ struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. } struct FarmInfo { IERC20 lpToken; IERC20 rewardToken; uint256 startBlock; uint256 blockReward; uint256 bonusEndBlock; uint256 bonus; uint256 endBlock; uint256 lastRewardBlock; // Last block number that reward distribution occurs. uint256 accRewardPerShare; // Accumulated Rewards per share, times 1e12 uint256 farmableSupply; // set in init, total amount of tokens farmable uint256 numFarmers; } /* ============ State Variables ============ */ // Useful for back-end systems to know how to read the contract (ABI) as we plan to launch multiple farm types uint256 public farmType = 1; IFarmFactory public factory; address public farmGenerator; FarmInfo public farmInfo; // Information on each user than stakes LP tokens mapping (address => UserInfo) public userInfo; /* ============ Events ============ */ event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event WithdrawWithoutReward(address indexed user, uint256 amount); /* ============ Constructor ============ */ /** * Store factory and generator instance. * * @param _factory Instance of Farm Factory * @param _farmGenerator Instance of Farm Generator */ constructor(address _factory, address _farmGenerator) public { factory = IFarmFactory(_factory); farmGenerator = _farmGenerator; } /* ============ Public/External functions ============ */ /** * Initialize the farming contract. This is called only once upon farm creation and the FarmGenerator * ensures the farm has the correct paramaters * * @param _rewardToken Instance of reward token contract * @param _amount Total sum of reward * @param _lpToken Instance of LP token contract * @param _blockReward Reward per block * @param _startBlock Block number to start reward * @param _bonusEndBlock Block number to end the bonus reward * @param _bonus Bonus multipler which will be applied until bonus end block */ function init( IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus ) external { require(msg.sender == address(farmGenerator), "FORBIDDEN"); _rewardToken.safeTransferFrom(msg.sender, address(this), _amount); farmInfo.rewardToken = _rewardToken; farmInfo.startBlock = _startBlock; farmInfo.blockReward = _blockReward; farmInfo.bonusEndBlock = _bonusEndBlock; farmInfo.bonus = _bonus; uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock; farmInfo.lpToken = _lpToken; farmInfo.lastRewardBlock = lastRewardBlock; farmInfo.accRewardPerShare = 0; farmInfo.endBlock = _endBlock; farmInfo.farmableSupply = _amount; } /** * Updates pool information to be up to date to the current block */ function updatePool() public { if (block.number <= farmInfo.lastRewardBlock) { return; } uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (lpSupply == 0) { farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock; return; } uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(farmInfo.blockReward); farmInfo.accRewardPerShare = farmInfo.accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply)); farmInfo.lastRewardBlock = block.number < farmInfo.endBlock ? block.number : farmInfo.endBlock; } /** * Deposit LP token function for msg.sender * * @param _amount the total deposit amount */ function deposit(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; updatePool(); if (user.amount > 0) { uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(msg.sender, pending); } if (user.amount == 0 && _amount > 0) { factory.userEnteredFarm(msg.sender); farmInfo.numFarmers++; } farmInfo.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12); emit Deposit(msg.sender, _amount); } /** * Withdraw LP token function for msg.sender * * @param _amount the total withdrawable amount */ function withdraw(uint256 _amount) external { UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount, "INSUFFICIENT"); updatePool(); if (user.amount == _amount && _amount > 0) { factory.userLeftFarm(msg.sender); farmInfo.numFarmers--; } uint256 pending = user.amount.mul(farmInfo.accRewardPerShare).div(1e12).sub(user.rewardDebt); _safeRewardTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(farmInfo.accRewardPerShare).div(1e12); farmInfo.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _amount); } /** * Function to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens */ function withdrawWithoutReward() external { UserInfo storage user = userInfo[msg.sender]; farmInfo.lpToken.safeTransfer(address(msg.sender), user.amount); emit WithdrawWithoutReward(msg.sender, user.amount); if (user.amount > 0) { factory.userLeftFarm(msg.sender); farmInfo.numFarmers--; } user.amount = 0; user.rewardDebt = 0; } /** * Withdraw tokens emergency. * * @param _token Token contract address * @param _to Address where the token withdraw to * @param _amount Amount of tokens to withdraw */ function emergencyWithdraw(address _token, address _to, uint256 _amount) external onlyOwner { IERC20 erc20Token = IERC20(_token); require(erc20Token.balanceOf(address(this)) > 0, "Insufficient balane"); uint256 amountToWithdraw = _amount; if (_amount == 0) { amountToWithdraw = erc20Token.balanceOf(address(this)); } erc20Token.safeTransfer(_to, amountToWithdraw); } /* ============ View functions ============ */ /** * Get the reward multiplier over the given _from_block until _to block * * @param _fromBlock the start of the period to measure rewards for * @param _to the end of the period to measure rewards for * * @return The weighted multiplier for the given period */ function getMultiplier(uint256 _fromBlock, uint256 _to) public view returns (uint256) { uint256 _from = _fromBlock >= farmInfo.startBlock ? _fromBlock : farmInfo.startBlock; uint256 to = farmInfo.endBlock > _to ? _to : farmInfo.endBlock; if (to <= farmInfo.bonusEndBlock) { return to.sub(_from).mul(farmInfo.bonus); } else if (_from >= farmInfo.bonusEndBlock) { return to.sub(_from); } else { return farmInfo.bonusEndBlock.sub(_from).mul(farmInfo.bonus).add( to.sub(farmInfo.bonusEndBlock) ); } } /** * Function to see accumulated balance of reward token for specified user * * @param _user the user for whom unclaimed tokens will be shown * * @return total amount of withdrawable reward tokens */ function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = farmInfo.accRewardPerShare; uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (block.number > farmInfo.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(farmInfo.blockReward); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } /* ============ Internal functions ============ */ /** * Safe reward transfer function, just in case a rounding error causes pool to not have enough reward tokens * * @param _to the user address to transfer tokens to * @param _amount the total amount of tokens to transfer */ function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = farmInfo.rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { farmInfo.rewardToken.transfer(_to, rewardBal); } else { farmInfo.rewardToken.transfer(_to, _amount); } } } // Root file: contracts/farm/FarmGenerator.sol pragma solidity 0.6.10; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { IFarmFactory } from "contracts/interfaces/IFarmFactory.sol"; // import { Farm } from "contracts/farm/Farm.sol"; contract FarmGenerator is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ============ Struct ============ */ struct FarmParameters { uint256 bonusBlocks; uint256 totalBonusReward; uint256 numBlocks; uint256 endBlock; uint256 requiredAmount; } /* ============ State Variables ============ */ IFarmFactory public factory; /* ============ Events ============ */ event FarmCreated( IERC20 rewardToken, uint256 amount, IERC20 lpToken, uint256 blockReward, uint256 startBlock, uint256 bonusEndBlock, uint256 bonus ); /* ============ Constructor ============ */ /** * Store factory instance. * * @param _factory Instance of Farm Factory contract */ constructor(IFarmFactory _factory) public { factory = _factory; } /** * Determine the endBlock based on inputs. Used on the front end to show the exact settings the Farm contract * will be deployed with * * @param _amount Total sum of reward * @param _blockReward Reward per block * @param _startBlock Block number to start reward * @param _bonusEndBlock Block number to end the bonus reward * @param _bonus Bonus multipler which will be applied until bonus end block */ function determineEndBlock( uint256 _amount, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus ) public pure returns (uint256, uint256) { FarmParameters memory params; params.bonusBlocks = _bonusEndBlock.sub(_startBlock); params.totalBonusReward = params.bonusBlocks.mul(_bonus).mul(_blockReward); params.numBlocks = _amount.sub(params.totalBonusReward).div(_blockReward); params.endBlock = params.numBlocks.add(params.bonusBlocks).add(_startBlock); uint256 nonBonusBlocks = params.endBlock.sub(_bonusEndBlock); uint256 effectiveBlocks = params.bonusBlocks.mul(_bonus).add(nonBonusBlocks); uint256 requiredAmount = _blockReward.mul(effectiveBlocks); return (params.endBlock, requiredAmount); } /** * Determine the blockReward based on inputs specifying an end date. Used on the front end to show the exact settings * the Farm contract will be deployed with * * @param _amount Total sum of reward * @param _startBlock Block number to start reward * @param _bonusEndBlock Block number to end the bonus reward * @param _bonus Bonus multipler which will be applied until bonus end block * @param _endBlock Block number to end reward */ function determineBlockReward( uint256 _amount, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus, uint256 _endBlock ) public pure returns (uint256, uint256) { uint256 bonusBlocks = _bonusEndBlock.sub(_startBlock); uint256 nonBonusBlocks = _endBlock.sub(_bonusEndBlock); uint256 effectiveBlocks = bonusBlocks.mul(_bonus).add(nonBonusBlocks); uint256 blockReward = _amount.div(effectiveBlocks); uint256 requiredAmount = blockReward.mul(effectiveBlocks); return (blockReward, requiredAmount); } /** * Creates a new Farm contract and registers it in the farm factory. Farming rewards are locked in the farm * * @param _rewardToken Instance of reward token contract * @param _amount Total sum of reward * @param _lpToken Instance of LP token contract * @param _blockReward Reward per block * @param _startBlock Block number to start reward * @param _bonusEndBlock Block number to end the bonus reward * @param _bonus Bonus multipler which will be applied until bonus end block * @param _manager Manager of the farm */ function createFarm( IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus, address _manager ) public onlyOwner returns (address) { require(_startBlock > block.number, "START"); // ideally at least 24 hours more to give farmers time require(_bonus > 0, "BONUS"); require(address(_rewardToken) != address(0), "TOKEN"); require(_blockReward > 1000, "BR"); // minimum 1000 divisibility per block reward (uint256 endBlock, uint256 requiredAmount) = determineEndBlock(_amount, _blockReward, _startBlock, _bonusEndBlock, _bonus); _rewardToken.safeTransferFrom(address(msg.sender), address(this), requiredAmount); Farm newFarm = new Farm(address(factory), address(this)); newFarm.transferOwnership(_manager); _rewardToken.safeApprove(address(newFarm), requiredAmount); newFarm.init(_rewardToken, requiredAmount, _lpToken, _blockReward, _startBlock, endBlock, _bonusEndBlock, _bonus); factory.registerFarm(address(newFarm)); emit FarmCreated(_rewardToken, _amount, _lpToken, _blockReward, _startBlock, _bonusEndBlock, _bonus); return (address(newFarm)); } }
Function to see accumulated balance of reward token for specified user _user the user for whom unclaimed tokens will be shown return total amount of withdrawable reward tokens/
function pendingReward(address _user) external view returns (uint256) { UserInfo storage user = userInfo[_user]; uint256 accRewardPerShare = farmInfo.accRewardPerShare; uint256 lpSupply = farmInfo.lpToken.balanceOf(address(this)); if (block.number > farmInfo.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(farmInfo.lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(farmInfo.blockReward); accRewardPerShare = accRewardPerShare.add(tokenReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); }
2,175,036
pragma solidity 0.5.0; import './Player.sol'; contract TiCtAcToE { uint8 leftMoves; bool public isReady; address public activeUser; address public gm; address public player1; // 1 = o address public player2; // 7 = x uint8[][] public board; address public winner = address(0); uint256 public lastTime; event UserMoved(address player, uint col, uint row ) ; constructor() public { gm = msg.sender; isReady = true; leftMoves = 9; initArray(); } modifier onlyActiveUser() { require(msg.sender == activeUser, "Only active user can make a move"); _; } modifier onlyGameManager() { require(msg.sender == gm, "Only active gm can make a move"); _; } function initArray() internal { board = new uint8[][](3); for (uint8 i = 0; i < 3; i++) { uint8[] memory temp = new uint8[](3); for(uint8 j = 0; j < 3; j++){ temp[j] = 0; } board[i] = temp; } } function setUser(address user) public{ require( player1 == address(0) || player2 == address(0), "two players are in the game" ); if(player1 == address(0)){ player1 = user; }else if(player2 == address(0)){ player2 = user; activeUser = player2; isReady = false; for(uint8 i = 0; i < 3; i++ ){ for(uint8 j = 0; j < 3; j++ ){ board[i][j] = 0; } } } } function move(uint8 col, uint8 row) public onlyActiveUser { require(isReady == false, "game is not ready"); require(winner == address(0), "Winner is set now "); require(leftMoves > 0, "there is no moves left"); require(row < 3 && col < 3, "illegal move"); require(board[col][row] == 0, "the cell is already used by another player"); lastTime = block.timestamp; leftMoves = leftMoves - 1; if(msg.sender == player1 ){ board[col][row] = board[col][row] + 1; activeUser = player2; } else if(msg.sender == player2) { board[col][row] = board[col][row] + 7; activeUser = player1; } if(checkWinner() || leftMoves == 0){ reward(); } emit UserMoved(activeUser ,col , row ); } function checkWinner() internal returns(bool){ //[(0,0),(0,1),(0,2)] //[(1,0),(1,1),(1,2)] //[(2,0),(2,1),(2,2)] uint8 mainDiagSum = 0; uint8 diagSum = 0; for (uint8 i = 0; i < 3; i++) { uint8 rowSum = 0; uint8 colSum = 0; for(uint8 j = 0; j < 3; j++){ rowSum += board[i][j]; colSum += board[j][i]; if (i == j) { mainDiagSum = mainDiagSum + board[i][i]; } if (i + j == 2) { diagSum += board[j][i]; } } // check rows and columns if (rowSum == 3 || colSum == 3) { winner = player1; return true; } else if (rowSum == 21 || colSum == 21) { winner = player2; return true; } } // check diagonals if (mainDiagSum == 3 || diagSum == 3) { winner = player1; return true; } else if (mainDiagSum == 21 || diagSum == 21) { winner = player2; return true; } return false; } function reward() internal{ if(winner == player1){ Player(player1).incWins(); Player(player2).incLosses(); }else if(winner == player2){ Player(player2).incWins(); Player(player1).incLosses(); }else{ Player(player2).incLosses(); Player(player1).incLosses(); } } function closeTable() public{ if(winner == player1){ winner == player2; }else if(winner == player2){ winner == player1; } reward(); } function checkTime() public{ if(block.timestamp - lastTime >= 60 ){ closeTable(); } } }
[(0,0),(0,1),(0,2)][(1,0),(1,1),(1,2)][(2,0),(2,1),(2,2)] check rows and columns check diagonals
function checkWinner() internal returns(bool){ uint8 mainDiagSum = 0; uint8 diagSum = 0; for (uint8 i = 0; i < 3; i++) { uint8 rowSum = 0; uint8 colSum = 0; for(uint8 j = 0; j < 3; j++){ rowSum += board[i][j]; colSum += board[j][i]; if (i == j) { mainDiagSum = mainDiagSum + board[i][i]; } if (i + j == 2) { diagSum += board[j][i]; } } if (rowSum == 3 || colSum == 3) { winner = player1; return true; winner = player2; return true; } } if (mainDiagSum == 3 || diagSum == 3) { winner = player1; return true; winner = player2; return true; } return false; }
6,432,680
pragma solidity 0.5.11; pragma experimental ABIEncoderV2; import "./QuasarPool.sol"; import "../../src/framework/PlasmaFramework.sol"; import "../../src/exits/payment/PaymentExitGame.sol"; import "../../src/utils/PosLib.sol"; import "../../src/utils/Merkle.sol"; import "../../src/exits/utils/ExitId.sol"; import "../../src/exits/payment/routers/PaymentInFlightExitRouter.sol"; import "../../src/utils/SafeEthTransfer.sol"; import "../../src/transactions/PaymentTransactionModel.sol"; import "../../src/transactions/GenericTransaction.sol"; import "../../src/exits/utils/MoreVpFinalization.sol"; import "../../src/exits/interfaces/ISpendingCondition.sol"; import "../../src/exits/registries/SpendingConditionRegistry.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol"; /** * @title Quasar Contract * Implementation Doc - https://github.com/omgnetwork/research-workshop/blob/master/Incognito_fast_withdrawals.md */ contract Quasar is QuasarPool { using SafeERC20 for IERC20; using SafeMath for uint256; using SafeMath for uint64; using PosLib for PosLib.Position; PlasmaFramework public plasmaFramework; // This contract works with the current exit game // Any changes to the exit game would require modifications to this contract // Verify the exit game before interacting PaymentExitGame public paymentExitGame; SpendingConditionRegistry public spendingConditionRegistry; address public quasarOwner; uint256 public safeBlockMargin; uint256 public waitingPeriod; uint256 constant public TICKET_VALIDITY_PERIOD = 14400; uint256 constant public IFE_CLAIM_MARGIN = 28800; // 7+1 days waiting period for IFE Claims uint256 constant public IFE_CLAIM_WAITING_PERIOD = 691200; uint256 public bondValue; // bond is added to this reserve only when tickets are flushed, bond is returned every other time uint256 public unclaimedBonds; bool public isPaused; struct Ticket { address payable outputOwner; uint256 validityTimestamp; uint256 reservedAmount; address token; uint256 bondValue; bytes rlpOutputCreationTx; bool isClaimed; } struct Claim { bytes rlpClaimTx; uint256 finalizationTimestamp; bool isValid; } mapping (uint256 => Ticket) public ticketData; mapping (uint256 => Claim) private ifeClaimData; event NewTicketObtained(uint256 utxoPos); event IFEClaimSubmitted(uint256 utxoPos, uint168 exitId); modifier onlyQuasarMaintainer() { require(msg.sender == quasarMaintainer, "Only the Quasar Maintainer can invoke this method"); _; } modifier onlyWhenNotPaused() { require(!isPaused, "The Quasar contract is paused"); _; } /** * @dev Constructor, takes params to set up quasar contract * @param plasmaFrameworkContract Plasma Framework contract address * @param _quasarOwner Receiver address on Plasma * @param _safeBlockMargin The Quasar will not accept exits for outputs younger than the current plasma block minus the safe block margin * @param _waitingPeriod Waiting period from submission to processing claim * @param _bondValue bond to obtain tickets */ constructor ( address plasmaFrameworkContract, address spendingConditionRegistryContract, address _quasarOwner, uint256 _safeBlockMargin, uint256 _waitingPeriod, uint256 _bondValue ) public { plasmaFramework = PlasmaFramework(plasmaFrameworkContract); paymentExitGame = PaymentExitGame(plasmaFramework.exitGames(1)); spendingConditionRegistry = SpendingConditionRegistry(spendingConditionRegistryContract); quasarOwner = _quasarOwner; quasarMaintainer = msg.sender; safeBlockMargin = _safeBlockMargin; waitingPeriod = _waitingPeriod; bondValue = _bondValue; unclaimedBonds = 0; } /** * @return The latest safe block number */ function getLatestSafeBlock() public view returns(uint256) { uint256 childBlockInterval = plasmaFramework.childBlockInterval(); uint currentPlasmaBlock = plasmaFramework.nextChildBlock().sub(childBlockInterval); return currentPlasmaBlock.sub(safeBlockMargin.mul(childBlockInterval)); } //////////////////////////////////////////// // Maintenance methods //////////////////////////////////////////// /** * @dev Set the safe block margin. * @param margin the new safe block margin */ function setSafeBlockMargin (uint256 margin) public onlyQuasarMaintainer() { safeBlockMargin = margin; } /** * @dev Flush an expired ticket to free up reserved funds * @notice Only an unclaimed ticket can be flushed, bond amount is added to unclaimedBonds * @param utxoPos pos of the output, which is the ticket identifier */ function flushExpiredTicket(uint256 utxoPos) public { uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp; require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed"); require(block.timestamp > expiryTimestamp && expiryTimestamp != 0, "Ticket still valid or doesn't exist"); uint256 tokenAmount = ticketData[utxoPos].reservedAmount; ticketData[utxoPos].reservedAmount = 0; ticketData[utxoPos].validityTimestamp = 0; tokenUsableCapacity[ticketData[utxoPos].token] = tokenUsableCapacity[ticketData[utxoPos].token].add(tokenAmount); unclaimedBonds = unclaimedBonds.add(ticketData[utxoPos].bondValue); } /** * @dev Pause contract in a byzantine state */ function pauseQuasar() public onlyQuasarMaintainer() { isPaused = true; } /** * @dev Unpause contract and allow tickets */ function resumeQuasar() public onlyQuasarMaintainer() { isPaused = false; } /** * @dev Withdraw Unclaimed bonds from the contract */ function withdrawUnclaimedBonds() public onlyQuasarMaintainer() { uint256 amount = unclaimedBonds; unclaimedBonds = 0; SafeEthTransfer.transferRevertOnError(msg.sender, amount, SAFE_GAS_STIPEND); } //////////////////////////////////////////// // Exit procedure //////////////////////////////////////////// /** * @dev Obtain a ticket from the Quasar * @notice Ticket is valid for four hours, pay bond here for obtaining ticket * @param utxoPos Output that will be spent to the quasar later, is the ticket identifier * @param rlpOutputCreationTx RLP-encoded transaction that created the output * @param outputCreationTxInclusionProof Transaction inclusion proof */ function obtainTicket(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory outputCreationTxInclusionProof) public payable onlyWhenNotPaused() { require(msg.value == bondValue, "Bond Value incorrect"); require(!ticketData[utxoPos].isClaimed, "The UTXO has already been claimed"); require(ticketData[utxoPos].validityTimestamp == 0, "This UTXO already has a ticket"); PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos); require(utxoPosDecoded.blockNum <= getLatestSafeBlock(), "The UTXO is from a block later than the safe limit"); PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(rlpOutputCreationTx); FungibleTokenOutputModel.Output memory outputData = PaymentTransactionModel.getOutput(decodedTx, utxoPosDecoded.outputIndex); // verify the owner of output is obtaining the ticket require(verifyOwnership(outputData, msg.sender), "Was not called by the Output owner"); require(MoreVpFinalization.isStandardFinalized( plasmaFramework, rlpOutputCreationTx, utxoPosDecoded.toStrictTxPos(), outputCreationTxInclusionProof ), "Provided Tx doesn't exist"); require(outputData.amount <= tokenUsableCapacity[outputData.token], "Requested amount exceeds the Usable Liqudity"); require(outputData.amount != 0, "Requested amount cannot be zero"); tokenUsableCapacity[outputData.token] = tokenUsableCapacity[outputData.token].sub(outputData.amount); ticketData[utxoPos] = Ticket(msg.sender, block.timestamp.add(TICKET_VALIDITY_PERIOD), outputData.amount, outputData.token, msg.value, rlpOutputCreationTx, false); emit NewTicketObtained(utxoPos); } // for simplicity fee has to be from a seperate input in the tx to quasar /** * @dev Submit claim after spending the output to the quasar owner * @param utxoPos pos of the output, which is the ticket identifier * @param utxoPosQuasarOwner pos of the quasar owner's output * @param rlpTxToQuasarOwner RLP-encoded transaction that spends the output to quasar owner * @param txToQuasarOwnerInclusionProof Transaction Inclusion proof */ function claim( uint256 utxoPos, uint256 utxoPosQuasarOwner, bytes memory rlpTxToQuasarOwner, bytes memory txToQuasarOwnerInclusionProof ) public { verifyTicketValidityForClaim(utxoPos); verifyClaimTxCorrectlyFormed(utxoPos, rlpTxToQuasarOwner); PosLib.Position memory utxoQuasarOwnerDecoded = PosLib.decode(utxoPosQuasarOwner); require(MoreVpFinalization.isStandardFinalized( plasmaFramework, rlpTxToQuasarOwner, utxoQuasarOwnerDecoded.toStrictTxPos(), txToQuasarOwnerInclusionProof ), "Provided Tx doesn't exist"); ticketData[utxoPos].isClaimed = true; address payable outputOwner = ticketData[utxoPos].outputOwner; address token = ticketData[utxoPos].token; if (token == address(0)) { uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue); SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND); } else { IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount); SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND); } } /** * @dev Submit an IFE claim for claims without inclusion proof * @param utxoPos pos of the output, which is the ticket identifier * @param inFlightClaimTx in-flight tx that spends the output to quasar owner */ function ifeClaim(uint256 utxoPos, bytes memory inFlightClaimTx) public { verifyTicketValidityForClaim(utxoPos); verifyClaimTxCorrectlyFormed(utxoPos, inFlightClaimTx); //verify IFE started uint168 exitId = ExitId.getInFlightExitId(inFlightClaimTx); uint168[] memory exitIdArr = new uint168[](1); exitIdArr[0] = exitId; PaymentExitDataModel.InFlightExit[] memory ifeData = paymentExitGame.inFlightExits(exitIdArr); require(ifeData[0].exitStartTimestamp != 0, "IFE has not been started"); // IFE claims should start within IFE_CLAIM_MARGIN from starting IFE to enable sufficient time to piggyback // this might be overriden by the ticket expiry check usually, except if the ticket is obtained later require(block.timestamp <= ifeData[0].exitStartTimestamp.add(IFE_CLAIM_MARGIN), "IFE Claim period has passed"); ticketData[utxoPos].isClaimed = true; ifeClaimData[utxoPos] = Claim(inFlightClaimTx, block.timestamp.add(IFE_CLAIM_WAITING_PERIOD), true); emit IFEClaimSubmitted(utxoPos, exitId); } /** * @dev Challenge an IFE claim * @notice A challenge is required if any of the claimTx's inputs are double spent * @param utxoPos pos of the output, which is the ticket identifier * @param rlpChallengeTx RLP-encoded challenge transaction * @param challengeTxInputIndex index pos of the same utxo in the challenge transaction * @param challengeTxWitness Witness for challenging transaction * @param otherInputIndex (optional) index pos of another input from the claimTx that is spent * @param otherInputCreationTx (optional) Transaction that created this shared input * @param senderData A keccak256 hash of the sender's address */ function challengeIfeClaim( uint256 utxoPos, bytes memory rlpChallengeTx, uint16 challengeTxInputIndex, bytes memory challengeTxWitness, uint16 otherInputIndex, bytes memory otherInputCreationTx, bytes32 senderData ) public { require(senderData == keccak256(abi.encodePacked(msg.sender)), "Incorrect SenderData"); require(ticketData[utxoPos].isClaimed && ifeClaimData[utxoPos].isValid, "The claim is not challengeable"); require(block.timestamp <= ifeClaimData[utxoPos].finalizationTimestamp, "The challenge period is over"); require( keccak256(ifeClaimData[utxoPos].rlpClaimTx) != keccak256(rlpChallengeTx), "The challenging transaction is the same as the claim transaction" ); require(MoreVpFinalization.isProtocolFinalized( plasmaFramework, rlpChallengeTx ), "The challenging transaction is invalid"); if (otherInputCreationTx.length == 0) { verifySpendingCondition(utxoPos, ticketData[utxoPos].rlpOutputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness); } else { PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(ifeClaimData[utxoPos].rlpClaimTx); verifySpendingCondition(uint256(decodedTx.inputs[otherInputIndex]), otherInputCreationTx, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness); } ifeClaimData[utxoPos].isValid = false; Ticket memory ticket = ticketData[utxoPos]; tokenUsableCapacity[ticket.token] = tokenUsableCapacity[ticket.token].add(ticket.reservedAmount); SafeEthTransfer.transferRevertOnError(msg.sender, ticket.bondValue, SAFE_GAS_STIPEND); } /** * @dev Process the IFE claim to get liquid funds * @param utxoPos pos of the output, which is the ticket identifier */ function processIfeClaim(uint256 utxoPos) public { require(block.timestamp > ifeClaimData[utxoPos].finalizationTimestamp, "The claim is not finalized yet"); require(ifeClaimData[utxoPos].isValid, "The claim has already been claimed or challenged"); address payable outputOwner = ticketData[utxoPos].outputOwner; ifeClaimData[utxoPos].isValid = false; address token = ticketData[utxoPos].token; if (token == address(0)) { uint256 totalAmount = ticketData[utxoPos].reservedAmount.add(ticketData[utxoPos].bondValue); SafeEthTransfer.transferRevertOnError(outputOwner, totalAmount, SAFE_GAS_STIPEND); } else { IERC20(token).safeTransfer(outputOwner, ticketData[utxoPos].reservedAmount); SafeEthTransfer.transferRevertOnError(outputOwner, ticketData[utxoPos].bondValue, SAFE_GAS_STIPEND); } } //////////////////////////////////////////// // Helper methods //////////////////////////////////////////// /** * @dev Verify the owner of the output * @param output Output Data * @param expectedOutputOwner expected owner of the output */ function verifyOwnership(FungibleTokenOutputModel.Output memory output, address expectedOutputOwner) private pure returns(bool) { address outputOwner = PaymentTransactionModel.getOutputOwner(output); return outputOwner == expectedOutputOwner; } /** * @dev Verify the challengeTx spends the output * @param utxoPos pos of the output * @param rlpOutputCreationTx transaction that created the output * @param rlpChallengeTx RLP-encoded challenge transaction * @param challengeTxInputIndex index pos of the same utxo in the challenge transaction * @param challengeTxWitness Witness for challenging transaction */ function verifySpendingCondition(uint256 utxoPos, bytes memory rlpOutputCreationTx, bytes memory rlpChallengeTx, uint16 challengeTxInputIndex, bytes memory challengeTxWitness) private { GenericTransaction.Transaction memory challengingTx = GenericTransaction.decode(rlpChallengeTx); GenericTransaction.Transaction memory inputTx = GenericTransaction.decode(rlpOutputCreationTx); PosLib.Position memory utxoPosDecoded = PosLib.decode(utxoPos); GenericTransaction.Output memory output = GenericTransaction.getOutput(inputTx, utxoPosDecoded.outputIndex); ISpendingCondition condition = spendingConditionRegistry.spendingConditions( output.outputType, challengingTx.txType ); require(address(condition) != address(0), "Spending condition contract not found"); bool isSpent = condition.verify( rlpOutputCreationTx, utxoPos, rlpChallengeTx, challengeTxInputIndex, challengeTxWitness ); require(isSpent, "Spending condition failed"); } /** * @dev Verify the validity of the ticket * @param utxoPos pos of the output, which is the ticket identifier */ function verifyTicketValidityForClaim(uint256 utxoPos) private { require(!ticketData[utxoPos].isClaimed, "Already claimed"); require(ticketData[utxoPos].outputOwner == msg.sender, "Not called by the ticket owner"); uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp; require(expiryTimestamp != 0 && block.timestamp <= expiryTimestamp, "Ticket is not valid"); } /** * @dev Verify the claim Tx is properly formed * @param utxoPos pos of the output, which is the ticket identifier * @param claimTx the Claim Tx to the quasar owner */ function verifyClaimTxCorrectlyFormed(uint256 utxoPos, bytes memory claimTx) private { PaymentTransactionModel.Transaction memory decodedTx = PaymentTransactionModel.decode(claimTx); // first input should be the Utxo with which ticket was obtained require(decodedTx.inputs[0] == bytes32(utxoPos), "The claim transaction does not spend the correct output"); // first output should be the utxo for Quasar owner FungibleTokenOutputModel.Output memory outputData = PaymentTransactionModel.getOutput(decodedTx, 0); // verify output to Quasar Owner require(verifyOwnership(outputData, quasarOwner), "The output is not owned by the quasar owner"); // considering fee as a separate input require(ticketData[utxoPos].reservedAmount == outputData.amount, "Wrong amount sent to quasar owner"); require(ticketData[utxoPos].token == outputData.token, "Wrong token sent to quasar owner"); } }
Verify the validity of the ticket utxoPos pos of the output, which is the ticket identifier/
function verifyTicketValidityForClaim(uint256 utxoPos) private { require(!ticketData[utxoPos].isClaimed, "Already claimed"); require(ticketData[utxoPos].outputOwner == msg.sender, "Not called by the ticket owner"); uint256 expiryTimestamp = ticketData[utxoPos].validityTimestamp; require(expiryTimestamp != 0 && block.timestamp <= expiryTimestamp, "Ticket is not valid"); }
6,460,158
./partial_match/100/0xdd85b1dbE3379AFA37F703822f9E328d4bAf8625/sources/contracts/interfaces/IBridge.sol
https:docs.tokenbridge.net/amb-bridge/development-of-a-cross-chain-application/how-to-develop-xchain-apps-by-ambcall-a-method-in-another-chain-using-the-amb-bridge
interface IAMB { function messageSender() external view returns (address); function messageSourceChainId() external view returns (bytes32); pragma solidity ^0.7.0; }
16,643,661
// SPDX-License-Identifier: MIT /* _____ __ __ ______ ______ ________ / |/ | / |/ | / \ / | $$$$$ |$$ | $$ |$$$$$$/ /$$$$$$ |$$$$$$$$/ $$ |$$ | $$ | $$ | $$ | $$/ $$ |__ __ $$ |$$ | $$ | $$ | $$ | $$ | / | $$ |$$ | $$ | $$ | $$ | __ $$$$$/ $$ \__$$ |$$ \__$$ | _$$ |_ $$ \__/ |$$ |_____ $$ $$/ $$ $$/ / $$ |$$ $$/ $$ | $$$$$$/ $$$$$$/ $$$$$$/ $$$$$$/ $$$$$$$$/ */ //This token is purely for use within the vApez ecosystem //It has no economic value whatsoever pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract Juice is ERC20Burnable, Ownable { uint256 public START_BLOCK; uint256 public BASE_RATE = 1 ether; address public vapezAddress; //mapping of address to rewards //Mapping of token to timestamp mapping(uint256 => uint256) internal lastClaimed; //Event for claiming juice event JuiceClaimed(address indexed user, uint256 reward); constructor(address _vapezAddress) ERC20("Juice", "JUICE") { setVapezAddress(_vapezAddress); START_BLOCK = block.timestamp; } function setVapezAddress(address _vapezAddress) public onlyOwner { vapezAddress = _vapezAddress; } function claimReward(uint256 _tokenId) public returns (uint256) { require( IERC721(vapezAddress).ownerOf(_tokenId) == msg.sender, "Caller does not own the vApe" ); //set last claim to start block if hasnt been claimed before if (lastClaimed[_tokenId] == uint256(0)) { lastClaimed[_tokenId] = START_BLOCK; } //compute JUICE to be claimed uint256 unclaimedJuice = computeRewards(_tokenId); lastClaimed[_tokenId] = block.timestamp; _mint(msg.sender, unclaimedJuice); emit JuiceClaimed(msg.sender, unclaimedJuice); return unclaimedJuice; } function claimRewards(uint256[] calldata _tokenIds) public returns (uint256) { uint256 totalUnclaimedJuice = 0; for (uint256 i = 0; i < _tokenIds.length; i++) { uint256 _tokenId = _tokenIds[i]; require( IERC721(vapezAddress).ownerOf(_tokenId) == msg.sender, "Caller does not own the vApe" ); if (lastClaimed[_tokenId] == uint256(0)) { lastClaimed[_tokenId] = START_BLOCK; } uint256 unclaimedJuice = computeRewards(_tokenId); totalUnclaimedJuice = totalUnclaimedJuice + unclaimedJuice; lastClaimed[_tokenId] = block.timestamp; } _mint(msg.sender, totalUnclaimedJuice); emit JuiceClaimed(msg.sender, totalUnclaimedJuice); return totalUnclaimedJuice; } //call this method to view how much JUICE you can get on a vape function computeRewards(uint256 _tokenId) public view returns (uint256) { uint256 timeToUse; timeToUse = lastClaimed[_tokenId]; if (lastClaimed[_tokenId] == uint256(0)) { timeToUse = START_BLOCK; } uint256 secondsElapsed = block.timestamp - timeToUse; uint256 accumulatedReward = (secondsElapsed * BASE_RATE) / 1 days; return accumulatedReward; } //call this method to compute the rewards for multiple vapez function computeMultipleRewards(uint256[] calldata _tokenIds) public view returns (uint256) { uint256 totalRewards = 0; for (uint256 index = 0; index < _tokenIds.length; index++) { totalRewards = totalRewards + computeRewards(_tokenIds[index]); } return totalRewards; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @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). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // 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 "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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); }
call this method to compute the rewards for multiple vapez
function computeMultipleRewards(uint256[] calldata _tokenIds) public view returns (uint256) { uint256 totalRewards = 0; for (uint256 index = 0; index < _tokenIds.length; index++) { totalRewards = totalRewards + computeRewards(_tokenIds[index]); } return totalRewards; }
10,090,347
./full_match/1/0x4CaE5458f76Fced0552FDd765DA5200565406841/sources/contracts/MultiVesting.sol
Creates vesting for beneficiary, with a given amount of funds to allocate, and timestamp of the allocation. _beneficiary - address of beneficiary. _amount - amount of tokens to allocate _startedAt - timestamp (in seconds) when the allocation should start
function addVesting( address _beneficiary, uint256 _amount, uint256 _startedAt ) public onlyOwner { require(_startedAt >= block.timestamp, "TIMESTAMP_CANNOT_BE_IN_THE_PAST"); require(_amount >= STEPS_AMOUNT, "VESTING_AMOUNT_TO_LOW"); uint256 debt = totalVestedAmount.sub(totalReleasedAmount); uint256 available = token.balanceOf(address(this)).sub(debt); require(available >= _amount, "DON_T_HAVE_ENOUGH"); Vesting memory v = Vesting({ startedAt: _startedAt, totalAmount: _amount, releasedAmount: 0 }); vestingMap[_beneficiary].push(v); totalVestedAmount = totalVestedAmount.add(_amount); }
3,861,643