comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * 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); }
0.6.10
/** * 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) ); } }
0.6.10
/** * 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); }
0.6.10
// END ONLY COLLABORATORS
function mint() external payable callerIsUser mintStarted { require(msg.value >= claimPrice, "Not enough Ether to mint a cube"); require( claimedTokenPerWallet[msg.sender] < maxClaimsPerWallet, "You cannot claim more cubes." ); require(totalMintedTokens < totalTokens, "No cubes left to be minted"); claimedTokenPerWallet[msg.sender]++; _mint(msg.sender, totalMintedTokens); totalMintedTokens++; }
0.8.4
/** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */
function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); if(!advIsCalc &&_getInStageIndex () > 0 && goalReached() && advWallet != address(0)) { //Send ETH to advisor, after to stage 1 uint256 advAmount = 0; advIsCalc = true; advAmount = weiRaised.mul(advPercent).div(100); vault.depositAdvisor(advWallet, advAmount); } }
0.4.21
/** @notice trustee will call the function to approve mint bToken @param _txid the transaction id of bitcoin @param _amount the amount to mint, 1BTC = 1bBTC = 1*10**18 weibBTC @param to mint to the address */
function approveMint( bytes32 _tunnelKey, string memory _txid, uint256 _amount, address to, string memory assetAddress ) public override whenNotPaused whenTunnelNotPause(_tunnelKey) onlyTrustee { if(to == address(0)) { if (approveFlag[_txid] == false) { approveFlag[_txid] = true; emit ETHAddressNotExist(_tunnelKey, _txid, _amount, to, msg.sender, assetAddress); } return; } uint256 trusteeCount = getRoleMemberCount(TRUSTEE_ROLE); bool shouldMint = mintProposal().approve( _tunnelKey, _txid, _amount, to, msg.sender, trusteeCount ); if (!shouldMint) { return; } uint256 canIssueAmount = tunnel(_tunnelKey).canIssueAmount(); bytes32 bTokenSymbolKey = tunnel(_tunnelKey).oTokenKey(); if (_amount.add(btoken(bTokenSymbolKey).totalSupply()) > canIssueAmount) { emit NotEnoughPledgeValue( _tunnelKey, _txid, _amount, to, msg.sender, assetAddress ); return; } // fee calculate in tunnel tunnel(_tunnelKey).issue(to, _amount); uint borMintAmount = calculateMintBORAmount(_tunnelKey, _amount); if(borMintAmount != 0) { amountByMint = amountByMint.add(borMintAmount); borERC20().transferFrom(mine, to, borMintAmount); } emit ApproveMintSuccess(_tunnelKey, _txid, _amount, to, assetAddress); }
0.6.12
/** * @dev Set the trust claim (msg.sender trusts subject) * @param _subject The trusted address */
function trust(address _subject) public onlyVoters { require(msg.sender != _subject); require(token != MintableTokenStub(0)); if (!trustRegistry[_subject].trustedBy[msg.sender]) { trustRegistry[_subject].trustedBy[msg.sender] = true; trustRegistry[_subject].totalTrust = trustRegistry[_subject].totalTrust.add(1); emit TrustSet(msg.sender, _subject); if (!voter[_subject] && isMajority(trustRegistry[_subject].totalTrust)) { voter[_subject] = true; voters = voters.add(1); emit VoteGranted(_subject); } return; } revert(); }
0.4.25
/** * @dev Unset the trust claim (msg.sender now reclaims trust from subject) * @param _subject The address of trustee to revoke trust */
function untrust(address _subject) public onlyVoters { require(token != MintableTokenStub(0)); if (trustRegistry[_subject].trustedBy[msg.sender]) { trustRegistry[_subject].trustedBy[msg.sender] = false; trustRegistry[_subject].totalTrust = trustRegistry[_subject].totalTrust.sub(1); emit TrustUnset(msg.sender, _subject); if (voter[_subject] && !isMajority(trustRegistry[_subject].totalTrust)) { voter[_subject] = false; // ToDo SafeMath voters = voters.sub(1); emit VoteRevoked(_subject); } return; } revert(); }
0.4.25
/** * @dev Proxy function to vote and mint tokens * @param to The address that will receive the minted tokens. * @param amount The amount of tokens to mint. * @param batchCode The detailed information on a batch. * @return A boolean that indicates if the operation was successful. */
function mint( address to, uint256 amount, string batchCode ) public onlyVoters returns (bool) { bytes32 proposalHash = keccak256(abi.encodePacked(to, amount, batchCode)); assert(!mintProposal[proposalHash].executed); if (!mintProposal[proposalHash].voted[msg.sender]) { if (mintProposal[proposalHash].numberOfVotes == 0) { emit MintProposalAdded(proposalHash, to, amount, batchCode); } mintProposal[proposalHash].numberOfVotes = mintProposal[proposalHash].numberOfVotes.add(1); mintProposal[proposalHash].voted[msg.sender] = true; emit MintProposalVoted(proposalHash, msg.sender, mintProposal[proposalHash].numberOfVotes); } if (isMajority(mintProposal[proposalHash].numberOfVotes)) { mintProposal[proposalHash].executed = true; token.mint(to, amount); emit MintProposalExecuted(proposalHash, to, amount, batchCode); } return (true); }
0.4.25
/* Transfer an amount from the owner's account to an indicated account */
function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && (! accountHasCurrentVote(msg.sender))) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } }
0.4.11
/* Create a new ballot and set the basic details (proposal description, dates) * The ballot still need to have options added and then to be sealed */
function adminAddBallot(string _proposal, uint256 _start, uint256 _end) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* Create and store the new ballot objects */ numBallots++; uint32 ballotId = numBallots; ballotNames[ballotId] = _proposal; ballotDetails[ballotId] = BallotDetails(_start, _end, 0, false); }
0.4.11
/* Add an option to an existing Ballot */
function adminAddBallotOption(uint32 _ballotId, string _option) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* store the new ballot option */ ballotDetails[_ballotId].numOptions += 1; uint32 optionId = ballotDetails[_ballotId].numOptions; ballotOptions[_ballotId][optionId] = _option; }
0.4.11
//Admin address
function changeAdmin(address newAdmin) public returns (bool) { require(msg.sender == admin); require(newAdmin != address(0)); uint256 balAdmin = balances[admin]; balances[newAdmin] = balances[newAdmin].add(balAdmin); balances[admin] = 0; admin = newAdmin; emit Transfer(admin, newAdmin, balAdmin); return true; }
0.4.24
/* Amend and option in an existing Ballot */
function adminEditBallotOption(uint32 _ballotId, uint32 _optionId, string _option) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* validate the ballot option */ require(_optionId > 0 && _optionId <= ballotDetails[_ballotId].numOptions); /* update the ballot option */ ballotOptions[_ballotId][_optionId] = _option; }
0.4.11
/* Seal a ballot - after this the ballot is official and no changes can be made. */
function adminSealBallot(uint32 _ballotId) { /* Admin functions must be called by the contract creator. */ require(msg.sender == m_administrator); /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* cannot change a ballot once it is sealed */ if(isBallotSealed(_ballotId)) { revert(); } /* set the ballot seal flag */ ballotDetails[_ballotId].sealed = true; }
0.4.11
/* function to allow a coin holder add to the vote count of an option in an * active ballot. The votes added equals the balance of the account. Once this is called successfully * the coins cannot be transferred out of the account until the end of the ballot. * * NB: The timing of the start and end of the voting period is determined by * the timestamp of the block in which the transaction is included. As given by * the current Ethereum standard this is *NOT* guaranteed to be accurate to any * given external time source. Therefore, votes should be placed well in advance * of the UTC end time of the Ballot. */
function vote(uint32 _ballotId, uint32 _selectedOptionId) { /* verify that the ballot exists */ require(_ballotId > 0 && _ballotId <= numBallots); /* Ballot must be in progress in order to vote */ require(isBallotInProgress(_ballotId)); /* Calculate the balance which which the coin holder has not yet voted, which is the difference between * the current balance for the senders address and the amount they already voted in this ballot. * If the difference is zero, this attempt to vote will fail. */ uint256 votableBalance = balanceOf(msg.sender) - ballotVoters[_ballotId][msg.sender]; require(votableBalance > 0); /* validate the ballot option */ require(_selectedOptionId > 0 && _selectedOptionId <= ballotDetails[_ballotId].numOptions); /* update the vote count and record the voter */ ballotVoteCount[_ballotId][_selectedOptionId] += votableBalance; ballotVoters[_ballotId][msg.sender] += votableBalance; }
0.4.11
/** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */
function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); }
0.8.9
// Convert an hexadecimal character to their value
function fromHexChar(uint8 c) public pure returns (uint8) { if (bytes1(c) >= bytes1('0') && bytes1(c) <= bytes1('9')) { return c - uint8(bytes1('0')); } if (bytes1(c) >= bytes1('a') && bytes1(c) <= bytes1('f')) { return 10 + c - uint8(bytes1('a')); } if (bytes1(c) >= bytes1('A') && bytes1(c) <= bytes1('F')) { return 10 + c - uint8(bytes1('A')); } require(false, "unknown variant"); }
0.7.6
// Convert an hexadecimal string to raw bytes
function fromHex(string memory s) public pure returns (bytes memory) { bytes memory ss = bytes(s); require(ss.length%2 == 0); // length must be even bytes memory r = new bytes(ss.length/2); for (uint i=0; i<ss.length/2; ++i) { r[i] = bytes1(fromHexChar(uint8(ss[2*i])) * 16 + fromHexChar(uint8(ss[2*i+1]))); } return r; }
0.7.6
// // #################################### // // tokenholder has to call approve(params: this SC address, amount in uint256) // method in Token SC, then he/she has to call refund() method in this // SC, all tokens from amount will be exchanged and the tokenholder will receive // his/her own ETH on his/her own address
function refund() external { // First phase uint256 i = getCurrentPhaseIndex(); require(i == 1 && !phases[i].IS_FINISHED, "Not Allowed phase"); address payable sender = _msgSender(); uint256 value = token.allowance(sender, address(this)); require(value > 0, "Not Allowed value"); uint256 topay_value = value.mul(_token_exchange_rate).div(10 ** 18); BurningRequiredValues(value, topay_value, address(this), address(this).balance); require(address(this).balance >= topay_value, "Insufficient funds"); require(token.transferFrom(sender, address(0), value), "Insufficient approve() value"); if (_burnt_amounts[sender] == 0) { _participants.push(sender); } _burnt_amounts[sender] = _burnt_amounts[sender].add(value); _totalburnt = _totalburnt.add(value); (bool success,) = sender.call{value : topay_value}(""); require(success, "Transfer failed"); emit LogRefundValue(msg.sender, topay_value); }
0.7.6
// View function to see pending votess on frontend.
function pendingvotes(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accVotesPerShare = pool.accVotesPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 votesReward = multiplier.mul(votesPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accVotesPerShare = accVotesPerShare.add(votesReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accVotesPerShare).div(1e12).sub(user.rewardDebt); }
0.6.12
// if somebody accidentally sends tokens to this SC directly you may use // burnTokensTransferredDirectly(params: tokenholder ETH address, amount in // uint256)
function refundTokensTransferredDirectly(address payable participant, uint256 value) external selfCall { uint256 i = getCurrentPhaseIndex(); require(i == 1, "Not Allowed phase"); // First phase uint256 topay_value = value.mul(_token_exchange_rate).div(10 ** uint256(token.decimals())); require(address(this).balance >= topay_value, "Insufficient funds"); require(token.transfer(address(0), value), "Error with transfer"); if (_burnt_amounts[participant] == 0) { _participants.push(participant); } _burnt_amounts[participant] = _burnt_amounts[participant].add(value); _totalburnt = _totalburnt.add(value); (bool success,) = participant.call{value : topay_value}(""); require(success, "Transfer failed"); emit LogRefundValue(participant, topay_value); }
0.7.6
// Deposit LP tokens to VotesPrinter for votes allocation.
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accVotesPerShare).div(1e12).sub(user.rewardDebt); safevotesTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accVotesPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
0.6.12
// Withdraw LP tokens from VotesPrinter.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accVotesPerShare).div(1e12).sub(user.rewardDebt); safevotesTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accVotesPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
0.6.12
/** * @notice Determine the endBlock based on inputs. Used on the front end to show the exact settings the Farm contract will be deployed with */
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); }
0.6.12
/** * @notice 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 */
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); }
0.6.12
/** * @notice Creates a new FarmUniswap contract and registers it in the * .sol. All farming rewards are locked in the FarmUniswap Contract */
function createFarmUniswap(IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, IUniFactory _swapFactory, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) 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), 'REWARD TOKEN'); require(_blockReward > 1000, 'BLOCK REWARD'); // minimum 1000 divisibility per block reward IUniFactory swapFactory = _swapFactory; // ensure this pair is on swapFactory by querying the factory IUniswapV2Pair lpair = IUniswapV2Pair(address(_lpToken)); address factoryPairAddress = swapFactory.getPair(lpair.token0(), lpair.token1()); require(factoryPairAddress == address(_lpToken), 'This pair is not on _swapFactory exchange'); FarmParameters memory params; (params.endBlock, params.requiredAmount) = determineEndBlock(_amount, _blockReward, _startBlock, _bonusEndBlock, _bonus); TransferHelper.safeTransferFrom(address(_rewardToken), address(_msgSender()), address(this), params.requiredAmount); FarmUniswap newFarm = new FarmUniswap(address(factory), address(this)); TransferHelper.safeApprove(address(_rewardToken), address(newFarm), params.requiredAmount); newFarm.init(_rewardToken, params.requiredAmount, _lpToken, _blockReward, _startBlock, params.endBlock, _bonusEndBlock, _bonus); factory.registerFarm(address(newFarm)); return (address(newFarm)); }
0.6.12
// This is a final distribution after phase 2 is fihished, everyone who left the // request with register() method will get remaining ETH amount // in proportion to their exchanged tokens
function startFinalDistribution(uint256 start_index, uint256 end_index) external onlyOwnerOrAdmin { require(end_index < getNumberOfParticipants()); uint256 j = getCurrentPhaseIndex(); require(j == 3 && !phases[j].IS_FINISHED, "Not Allowed phase"); // Final Phase uint256 pointfix = 1000000000000000000; // 10^18 for (uint i = start_index; i <= end_index; i++) { if(!isRegistration(_participants[i]) || isFinalWithdraw(_participants[i])){ continue; } uint256 piece = getBurntAmountByAddress(_participants[i]).mul(pointfix).div(sum_burnt_amount_registered); uint256 value = final_distribution_balance.mul(piece).div(pointfix); if (value > 0) { _is_final_withdraw[_participants[i]] = true; (bool success,) = _participants[i].call{value : value}(""); require(success, "Transfer failed"); emit LogWithdrawETH(_participants[i], value); } } }
0.7.6
// this method reverts the current phase to the previous one
function revertPhase() external selfCall { uint256 i = getCurrentPhaseIndex(); require(i > 0, "Initialize phase is already active"); phases[i].IS_STARTED = false; phases[i].IS_FINISHED = false; phases[i - 1].IS_STARTED = true; phases[i - 1].IS_FINISHED = false; }
0.7.6
/* Buying */
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) { if (_price < increaseLimit1) { return _price.mul(200).div(95); } else if (_price < increaseLimit2) { return _price.mul(135).div(96); } else if (_price < increaseLimit3) { return _price.mul(125).div(97); } else if (_price < increaseLimit4) { return _price.mul(117).div(97); } else { return _price.mul(115).div(98); } }
0.4.21
/** * Create presale contract where lock up period is given days */
function PresaleFundCollector(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit) { owner = _owner; // Give argument if(_freezeEndsAt == 0) { throw; } // Give argument if(_weiMinimumLimit == 0) { throw; } weiMinimumLimit = _weiMinimumLimit; freezeEndsAt = _freezeEndsAt; }
0.4.8
/** * Participate to a presale. */
function invest() public payable { // Cannot invest anymore through crowdsale when moving has begun if(moving) throw; address investor = msg.sender; bool existing = balances[investor] > 0; balances[investor] = balances[investor].plus(msg.value); // Need to fulfill minimum limit if(balances[investor] < weiMinimumLimit) { throw; } // This is a new investor if(!existing) { // Limit number of investors to prevent too long loops if(investorCount >= MAX_INVESTORS) throw; investors.push(investor); investorCount++; } Invested(investor, msg.value); }
0.4.8
/** * Load funds to the crowdsale for all investor. * */
function parcipateCrowdsaleAll() public { // We might hit a max gas limit in this loop, // and in this case you can simply call parcipateCrowdsaleInvestor() for all investors for(uint i=0; i<investors.length; i++) { parcipateCrowdsaleInvestor(investors[i]); } }
0.4.8
/** * ICO never happened. Allow refund. */
function refund() { // Trying to ask refund too soon if(now < freezeEndsAt) throw; // We have started to move funds moving = true; address investor = msg.sender; if(balances[investor] == 0) throw; uint amount = balances[investor]; delete balances[investor]; if(!investor.send(amount)) throw; Refunded(investor, amount); }
0.4.8
/** * @notice initialize the farming contract. This is called only once upon farm creation and the FarmGenerator ensures the farm has the correct paramaters */
function init( IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, uint256 _blockReward, uint256 _startBlock, uint256 _endBlock, uint256 _bonusEndBlock, uint256 _bonus ) public { address msgSender = _msgSender(); require(msgSender == address(farmGenerator), "FORBIDDEN"); TransferHelper.safeTransferFrom( address(_rewardToken), msgSender, 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; }
0.6.12
/** * @dev Mint pool shares for a given stake amount * @param _stakeAmount The amount of underlying to stake * @return shares The number of pool shares minted */
function mint(uint256 _stakeAmount) external returns (uint256 shares) { require( stakedToken.allowance(msg.sender, address(this)) >= _stakeAmount, "mint: insufficient allowance" ); // Grab the pre-deposit balance and shares for comparison uint256 oldBalance = stakedToken.balanceOf(address(this)); uint256 oldShares = totalSupply(); // Pull user's tokens into the pool stakedToken.safeTransferFrom(msg.sender, address(this), _stakeAmount); // Calculate the fee for minting uint256 fee = (_stakeAmount * mintFee) / 1e18; if (fee != 0) { stakedToken.safeTransfer(feePayee, fee); _stakeAmount -= fee; emit Fee(fee); } // Calculate the pool shares for the new deposit if (oldShares != 0) { // shares = stake * oldShares / oldBalance shares = (_stakeAmount * oldShares) / oldBalance; } else { // if no shares exist, just assign 1,000 shares (it's arbitrary) shares = 10**3; } // Transfer shares to caller _mint(msg.sender, shares); emit Deposit(msg.sender, _stakeAmount, shares); }
0.8.9
/** * @dev Burn some pool shares and claim the underlying tokens * @param _shareAmount The number of shares to burn * @return tokens The number of underlying tokens returned */
function burn(uint256 _shareAmount) external returns (uint256 tokens) { require(balanceOf(msg.sender) >= _shareAmount, "burn: insufficient shares"); // TODO: Extract // Calculate the user's share of the underlying balance uint256 balance = stakedToken.balanceOf(address(this)); tokens = (_shareAmount * balance) / totalSupply(); // Burn the caller's shares before anything else _burn(msg.sender, _shareAmount); // Calculate the fee for burning uint256 fee = getBurnFee(tokens); if (fee != 0) { tokens -= fee; stakedToken.safeTransfer(feePayee, fee); emit Fee(fee); } // Transfer underlying tokens back to caller stakedToken.safeTransfer(msg.sender, tokens); emit Payout(msg.sender, tokens, _shareAmount); }
0.8.9
/** * @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens */
function emergencyWithdraw() public { address msgSender = _msgSender(); UserInfo storage user = userInfo[msgSender]; farmInfo.lpToken.safeTransfer(address(msgSender), user.amount); emit EmergencyWithdraw(msgSender, user.amount); if (user.amount > 0) { factory.userLeftFarm(msgSender); farmInfo.numFarmers = farmInfo.numFarmers.sub(1); } user.amount = 0; user.rewardDebt = 0; }
0.6.12
/** * @dev Relay an index update that has been signed by an authorized proposer. * The signature provided must satisfy two criteria: * (1) the signature must be a valid EIP-712 signature for the proposal; and * (2) the signer must have the "PROPOSER" role. * @notice See https://docs.ethers.io/v5/api/signer/#Signer-signTypedData * @param relayed The relayed proposal * @param signature An EIP-712 signature for the proposal * @param signer The address of the EIP-712 signature provider * @return bond The bond amount claimable via successful dispute * @return proposalId The unique ID of the proposal * @return expiresAt The time at which the proposal is no longer disputable */
function relay( Proposal calldata relayed, bytes calldata signature, address signer ) external onlySignedProposals(relayed, signature, signer) returns ( uint256 bond, bytes32 proposalId, uint32 expiresAt ) { proposalId = _proposalId(relayed.timestamp, relayed.value, relayed.data); require(proposal[proposalId].timestamp == 0, "duplicate proposal"); Index storage _index = index[relayed.indexId]; require(_index.disputesOutstanding < 3, "index ineligible for proposals"); require( _index.lastUpdated < relayed.timestamp, "must be later than most recent proposal" ); bond = _index.bondAmount; expiresAt = uint32(block.timestamp) + _index.disputePeriod; proposal[proposalId] = relayed; _index.lastUpdated = relayed.timestamp; _issueRewards(relayed.indexId, msg.sender); emit Relayed(relayed.indexId, proposalId, relayed, msg.sender, bond); }
0.8.9
/** * @dev Disputes a proposal prior to its expiration. This causes a bond to be * posted on behalf of DAOracle stakers and an equal amount to be pulled from * the caller. * @notice This actually requests, proposes, and disputes with UMA's SkinnyOO * which sends the bonds and disputed proposal to UMA's DVM for settlement by * way of governance vote. Voters follow the specification of the DAOracle's * approved UMIP to determine the correct value. Once the outcome is decided, * the SkinnyOO will callback to this contract's `priceSettled` function. * @param proposalId the identifier of the proposal being disputed */
function dispute(bytes32 proposalId) external { Proposal storage _proposal = proposal[proposalId]; Index storage _index = index[_proposal.indexId]; require(proposal[proposalId].timestamp != 0, "proposal doesn't exist"); require( !isDisputed[proposalId] && block.timestamp < proposal[proposalId].timestamp + _index.disputePeriod, "proposal already disputed or expired" ); isDisputed[proposalId] = true; _index.dispute(_proposal, oracle, externalIdentifier); emit Disputed(_proposal.indexId, proposalId, msg.sender); }
0.8.9
/** * @dev External callback for UMA's SkinnyOptimisticOracle. Fired whenever a * disputed proposal has been settled by the DVM, regardless of outcome. * @notice This is always called by the UMA SkinnyOO contract, not an EOA. * @param - identifier, ignored * @param timestamp The timestamp of the proposal * @param ancillaryData The data field from the proposal * @param request The entire SkinnyOptimisticOracle Request object */
function priceSettled( bytes32, /** identifier */ uint32 timestamp, bytes calldata ancillaryData, SkinnyOptimisticOracleInterface.Request calldata request ) external onlyRole(ORACLE) { bytes32 id = _proposalId( timestamp, request.proposedPrice, bytes32(ancillaryData) ); Proposal storage relayed = proposal[id]; Index storage _index = index[relayed.indexId]; _index.bondsOutstanding -= request.bond; _index.disputesOutstanding--; isDisputed[id] = false; if (relayed.value != request.resolvedPrice) { // failed proposal, slash pool to recoup lost bond pool[request.currency].slash(_index.bondAmount, address(this)); } else { // successful proposal, return bond to sponsor request.currency.safeTransfer(_index.sponsor, request.bond); // sends the rest of the funds received to the staking pool request.currency.safeTransfer( address(pool[request.currency]), request.currency.balanceOf(address(this)) ); } emit Settled(relayed.indexId, id, relayed.value, request.resolvedPrice); }
0.8.9
/** * @dev Adds or updates a index. Can only be called by managers. * @param bondToken The token to be used for bonds * @param bondAmount The quantity of tokens to offer for bonds * @param indexId The price index identifier * @param disputePeriod The proposal dispute window * @param floor The starting portion of rewards payable to reporters * @param ceiling The maximum portion of rewards payable to reporters * @param tilt The rate of change from floor to ceiling per second * @param drop The number of reward tokens to drip (per second) * @param creatorAmount The portion of rewards payable to the methodologist * @param creatorAddress The recipient of the methodologist's rewards * @param sponsor The provider of funding for bonds and rewards */
function configureIndex( IERC20 bondToken, uint256 bondAmount, bytes32 indexId, uint32 disputePeriod, uint64 floor, uint64 ceiling, uint64 tilt, uint256 drop, uint64 creatorAmount, address creatorAddress, address sponsor ) external onlyRole(MANAGER) { Index storage _index = index[indexId]; _index.bondToken = bondToken; _index.bondAmount = bondAmount; _index.lastUpdated = _index.lastUpdated == 0 ? uint32(block.timestamp) : _index.lastUpdated; _index.drop = drop; _index.ceiling = ceiling; _index.tilt = tilt; _index.floor = floor; _index.creatorAmount = creatorAmount; _index.creatorAddress = creatorAddress; _index.disputePeriod = disputePeriod == 0 ? defaultDisputePeriod : disputePeriod; _index.sponsor = sponsor == address(0) ? address(_index.deploySponsorPool()) : sponsor; if (address(pool[bondToken]) == address(0)) { _createPool(_index); } emit IndexConfigured(indexId, bondToken); }
0.8.9
/** * @notice handle approvals of tokens that require approving from a base of 0 * @param token - the token we're approving * @param spender - entity the owner (sender) is approving to spend his tokens * @param amount - number of tokens being approved */
function safeApprove(IERC20 token, address spender, uint amount) internal returns (bool) { uint currentAllowance = token.allowance(address(this), spender); // Do nothing if allowance is already set to this value if(currentAllowance == amount) { return true; } // If approval is not zero reset it to zero first if(currentAllowance != 0) { return token.approve(spender, 0); } // do the actual approval return token.approve(spender, amount); }
0.6.12
/** * @notice Create a new CRP * @dev emits a LogNewCRP event * @param factoryAddress - the BFactory instance used to create the underlying pool * @param poolParams - struct containing the names, tokens, weights, balances, and swap fee * @param rights - struct of permissions, configuring this CRP instance (see above for definitions) */
function newCrp( address factoryAddress, ConfigurableRightsPool.PoolParams calldata poolParams, RightsManager.Rights calldata rights ) external returns (ConfigurableRightsPool) { require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ERR_TOO_FEW_TOKENS"); // Arrays must be parallel require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, "ERR_START_BALANCES_MISMATCH"); require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, "ERR_START_WEIGHTS_MISMATCH"); ConfigurableRightsPool crp = new ConfigurableRightsPool( factoryAddress, poolParams, rights ); emit LogNewCrp(msg.sender, address(crp)); _isCrp[address(crp)] = true; // The caller is the controller of the CRP // The CRP will be the controller of the underlying Core BPool crp.setController(msg.sender); return crp; }
0.6.12
/** * @notice Create a new ESP * @dev emits a LogNewESP event * @param factoryAddress - the BFactory instance used to create the underlying pool * @param poolParams - CRP pool parameters * @param rights - struct of permissions, configuring this CRP instance (see above for definitions) */
function newEsp( address factoryAddress, ConfigurableRightsPool.PoolParams calldata poolParams, RightsManager.Rights calldata rights ) external returns (ElasticSupplyPool) { require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ERR_TOO_FEW_TOKENS"); // Arrays must be parallel require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, "ERR_START_BALANCES_MISMATCH"); require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, "ERR_START_WEIGHTS_MISMATCH"); ElasticSupplyPool esp = new ElasticSupplyPool( factoryAddress, poolParams, rights ); emit LogNewEsp(msg.sender, address(esp)); _isEsp[address(esp)] = true; esp.setController(msg.sender); return esp; }
0.6.12
/** * Command Hash helper. * * Accepts alphanumeric characters, hyphens, periods, and underscores. * Returns a keccak256 hash of the lowercase command. */
function _commandHash(string memory str) private pure returns (bytes32){ bytes memory b = bytes(str); for (uint i; i<b.length; i++){ bytes1 char = b[i]; require ( (char >= 0x30 && char <= 0x39) || //0-9 (char >= 0x41 && char <= 0x5A) || //A-Z (char >= 0x61 && char <= 0x7A) || //a-z (char == 0x2D) || //- (char == 0x2E) || //. (char == 0x5F) //_ , "Command contains invalid characters."); } bytes memory bLower = new bytes(b.length); for (uint i = 0; i < b.length; i++) { if ((uint8(b[i]) >= 65) && (uint8(b[i]) <= 90)) { // Uppercase character bLower[i] = bytes1(uint8(b[i]) + 32); } else { bLower[i] = b[i]; } } return keccak256(abi.encode(string(bLower))); }
0.8.7
/** * Update a command. * * Requires ownership of token. */
function update(string memory _command, string memory _tokenURI) public { bytes32 _cmd = _commandHash(_command); uint tokenID = _commands[_cmd]; require(tokenID > 0, "Command not found."); require(ownerOf(tokenID) == msg.sender, "Only the owner can update the token."); require(!_frozen[tokenID], "Token is frozen and cannot be updated."); _setTokenURI(tokenID, _tokenURI); }
0.8.7
/** * Freeze a command. * * Requires ownership of token. */
function freeze(string memory _command) public { bytes32 _cmd = _commandHash(_command); uint tokenID = _commands[_cmd]; require(tokenID > 0, "Command not found."); require(ownerOf(tokenID) == msg.sender, "Only the owner can freeze the token."); require(!_frozen[tokenID], "Already frozen."); _frozen[tokenID] = true; }
0.8.7
// # Minting Helpers
function _safeMintQuantity(address to, uint quantity) private { uint fromTokenId = _totalMintedCount + 1; uint toTokenId = _totalMintedCount + quantity + 1; _totalMintedCount += quantity; for (uint i = fromTokenId; i < toTokenId; i++) { _safeMint(to, i); } }
0.8.4
// # Sale Mint
function presaleMint(uint[] calldata sacredDevilTokenIds, address to) external { uint quantity = sacredDevilTokenIds.length; _requireNotSoldOut(); require( // solhint-disable-next-line not-rely-on-time block.timestamp < PUBLIC_SALE_OPEN_TIME, "Presale has ended" ); _requireSaleNotPaused(); _requireValidQuantity(quantity); _requireEnoughSupplyRemaining(quantity); // Check the caller passed Sacred Devil token IDs that // - Caller owns the corresponding Sacred Devil tokens // - The Sacred Devil token ID has not been used before for (uint i = 0; i < quantity; i++) { uint256 sdTokenId = sacredDevilTokenIds[i]; address ownerOfSDToken = IERC721(DEVILS_CONTRACT_ADDRESS).ownerOf(sdTokenId); require( ownerOfSDToken == msg.sender, string(abi.encodePacked("You do not own LOSD#", Strings.toString(sdTokenId))) ); require( claimedDevils[sdTokenId] == false, string(abi.encodePacked("Already minted with LOSD#", Strings.toString(sdTokenId))) ); claimedDevils[sdTokenId] = true; } _saleMintedCount += quantity; _safeMintQuantity(to, quantity); }
0.8.4
// Mint new token(s)
function mint(uint8 _quantityToMint) public payable { require(_startDate <= block.timestamp || (block.timestamp >= _whitelistStartDate && _whitelisted[msg.sender] == true), block.timestamp <= _whitelistStartDate ? "Sale is not open" : "Not whitelisted"); require(_quantityToMint >= 1, "Must mint at least 1"); require(block.timestamp >= _whitelistStartDate && block.timestamp <= _startDate ? (_quantityToMint + balanceOf(msg.sender) <= 4) : true, "Whitelisted mints are limited to 4 per wallet"); require( _quantityToMint <= getCurrentMintLimit(), "Maximum current buy limit for individual transaction exceeded" ); require( (_quantityToMint + totalSupply()) <= maxSupply, "Exceeds maximum supply" ); require( msg.value == (getCurrentPrice() * _quantityToMint), "Ether submitted does not match current price" ); for (uint8 i = 0; i < _quantityToMint; i++) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); } }
0.8.3
// Withdraw ether from contract
function withdraw() public onlyOwner { require(address(this).balance > 0, "Balance must be positive"); uint256 _balance = address(this).balance; address _coldWallet = 0x9781F65af8324b40Ee9Ca421ea963642Bc8a8C2b; payable(_coldWallet).transfer((_balance * 9)/10); address _devWallet = 0x3097617CbA85A26AdC214A1F87B680bE4b275cD0; payable(_devWallet).transfer((_balance * 1)/10); }
0.8.3
/** * Same as buy, but explicitly sets your dividend percentage. * If this has been called before, it will update your `default' dividend * percentage for regular buy transactions going forward. */
function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string providedUnhashedPass) public payable returns (uint) { require(icoPhase || regularPhase); if (icoPhase) { // Anti-bot measures - not perfect, but should help some. bytes32 hashedProvidedPass = keccak256(providedUnhashedPass); // require(hashedProvidedPass == icoHashedPass || msg.sender == bankrollAddress); uint gasPrice = tx.gasprice; // Prevents ICO buyers from getting substantially burned if the ICO is reached // before their transaction is processed. //require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap); } // Dividend percentage should be a currently accepted value. require (validDividendRates_[_divChoice]); // Set the dividend fee percentage denominator. userSelectedRate[msg.sender] = true; userDividendRate[msg.sender] = _divChoice; emit UserDividendRate(msg.sender, _divChoice); // Finally, purchase tokens. purchaseTokens(msg.value, _referredBy); }
0.4.24
// Overload
function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice) public payable { require(regularPhase); address _customerAddress = msg.sender; uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender]; if (userSelectedRate[_customerAddress] && divChoice == 0) { purchaseTokens(msg.value, _referredBy); } else { buyAndSetDivPercentage(_referredBy, divChoice, "0x0"); } uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance); transferTo(msg.sender, target, difference, _data); }
0.4.24
// Fallback function only works during regular phase - part of anti-bot protection.
function() payable public { /** / If the user has previously set a dividend rate, sending / Ether directly to the contract simply purchases more at / the most recent rate. If this is their first time, they / are automatically placed into the 20% rate `bucket'. **/ require(regularPhase); address _customerAddress = msg.sender; if (userSelectedRate[_customerAddress]) { purchaseTokens(msg.value, 0x0); } else { buyAndSetDivPercentage(0x0, 20, "0x0"); } }
0.4.24
/** * Transfer tokens from the caller to a new holder: the Used By Smart Contracts edition. * No charge incurred for the transfer. No seriously, we'd make a terrible bank. */
function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns(bool) { // Setup variables address _customerAddress = _from; bytes memory empty; // Make sure we own the tokens we're transferring, are ALLOWED to transfer that many tokens, // and are transferring at least one full token. require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress] && _amountOfTokens <= allowed[_customerAddress][msg.sender]); transferFromInternal(_from, _toAddress, _amountOfTokens, empty); // Good old ERC20. return true; }
0.4.24
// Get the sell price at the user's average dividend rate
function sellPrice() public view returns(uint) { uint price; if (icoPhase || currentEthInvested < ethInvestedDuringICO) { price = tokenPriceInitial_; } else { // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedForEth = ethereumToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedForEth; } // Factor in the user's average dividend rate uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude)); return theSellPrice; }
0.4.24
// Get the buy price at a particular dividend rate
function buyPrice(uint dividendRate) public view returns(uint) { uint price; if (icoPhase || currentEthInvested < ethInvestedDuringICO) { price = tokenPriceInitial_; } else { // Calculate the tokens received for 100 finney. // Divide to find the average, to calculate the price. uint tokensReceivedForEth = ethereumToTokens_(0.001 ether); price = (1e18 * 0.001 ether) / tokensReceivedForEth; } // Factor in the user's selected dividend rate uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price); return theBuyPrice; }
0.4.24
// Called from transferFrom. Always checks if _customerAddress has dividends.
function withdrawFrom(address _customerAddress) internal { // Setup data uint _dividends = theDividendsOf(false, _customerAddress); // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); // Fire logging event. emit onWithdraw(_customerAddress, _dividends); }
0.4.24
/** * @dev Compute differ payment. * @param _ethAmount The amount of ETH entitled by the client. * @param _ethBalance The amount of ETH retained by the payment handler. * @return The amount of differed ETH payment. */
function computeDifferPayment(uint256 _ethAmount, uint256 _ethBalance) external view returns (uint256) { if (getPaymentQueue().getNumOfPayments() > 0) return _ethAmount; else if (_ethAmount > _ethBalance) return _ethAmount - _ethBalance; // will never underflow else return 0; }
0.4.25
/** * @dev Settle payments by chronological order of registration. * @param _maxNumOfPayments The maximum number of payments to handle. */
function settlePayments(uint256 _maxNumOfPayments) external { require(getSGRAuthorizationManager().isAuthorizedForPublicOperation(msg.sender), "settle payments is not authorized"); IETHConverter ethConverter = getETHConverter(); IPaymentHandler paymentHandler = getPaymentHandler(); IPaymentQueue paymentQueue = getPaymentQueue(); uint256 numOfPayments = paymentQueue.getNumOfPayments(); numOfPayments = numOfPayments.min(_maxNumOfPayments).min(maxNumOfPaymentsLimit); for (uint256 i = 0; i < numOfPayments; i++) { (address wallet, uint256 sdrAmount) = paymentQueue.getPayment(0); uint256 ethAmount = ethConverter.toEthAmount(sdrAmount); uint256 ethBalance = paymentHandler.getEthBalance(); if (ethAmount > ethBalance) { paymentQueue.updatePayment(ethConverter.fromEthAmount(ethAmount - ethBalance)); // will never underflow paymentHandler.transferEthToSgrHolder(wallet, ethBalance); emit PaymentPartialSettled(wallet, sdrAmount, ethBalance); break; } paymentQueue.removePayment(); paymentHandler.transferEthToSgrHolder(wallet, ethAmount); emit PaymentSettled(wallet, sdrAmount, ethAmount); } }
0.4.25
/** * @dev Set for what contract this rules are. * * @param src20 - Address of src20 contract. */
function setSRC(address src20) override external returns (bool) { require(doTransferCaller == address(0), "external contract already set"); require(address(_src20) == address(0), "external contract already set"); require(src20 != address(0), "src20 can not be zero"); doTransferCaller = _msgSender(); _src20 = src20; return true; }
0.8.7
/** * @dev Do transfer and checks where funds should go. If both from and to are * on the whitelist funds should be transferred but if one of them are on the * grey list token-issuer/owner need to approve transfer. * * param from The address to transfer from. * param to The address to send tokens to. * @param value The amount of tokens to send. */
function doTransfer(address from, address to, uint256 value) override external onlyDoTransferCaller returns (bool) { (from,to,value) = _doTransfer(from, to, value); if (isChainExists()) { require(ITransferRules(chainRuleAddr).doTransfer(msg.sender, to, value), "chain doTransfer failed"); } else { //_transfer(msg.sender, to, value); require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed"); } return true; }
0.8.7
//--------------------------------------------------------------------------------- // private section //---------------------------------------------------------------------------------
function _tryExternalSetSRC(address chainAddr) private returns (bool) { try ITransferRules(chainAddr).setSRC(_src20) returns (bool) { return (true); } catch Error(string memory /*reason*/) { // This is executed in case // revert was called inside getData // and a reason string was provided. return (false); } catch (bytes memory /*lowLevelData*/) { // This is executed in case revert() was used // or there was a failing assertion, division // by zero, etc. inside getData. return (false); } }
0.8.7
/** * init internal */
function __SimpleTransferRule_init( ) internal initializer { __BaseTransferRule_init(); //uniswapV2Pair = 0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa; uniswapV2Pairs.push(0x03B0da178FecA0b0BBD5D76c431f16261D0A76aa); _src20 = 0x6Ef5febbD2A56FAb23f18a69d3fB9F4E2A70440B; normalValueRatio = 10; // 6 months; dayInSeconds = 86400; lockupPeriod = dayInSeconds.mul(180); isTrading = 1; isTransfers = 1; }
0.8.7
// receive gambler's money and start betting
function () payable { require(msg.value >= minbet); require(msg.value <=maxbet); require(this.balance >= msg.value*2); luckynum = _getrand09(); if (luckynum < 5) { uint winvalue = msg.value*2*(10000-190)/10000; YouWin(msg.sender, msg.value, winvalue); msg.sender.transfer(winvalue); winlose = 'win'; } else{ YouLose(msg.sender, msg.value); msg.sender.transfer(1); winlose = 'lose'; } }
0.4.15
/** * amount that locked up for `addr` in `currentTime` */
function _minimumsGet( address addr, uint256 currentTime ) internal view returns (uint256) { uint256 minimum = 0; uint256 c = _minimums[addr].length; uint256 m; for (uint256 i=0; i<c; i++) { if ( _minimums[addr][i].startTime > currentTime || _minimums[addr][i].endTime < currentTime ) { continue; } m = _minimums[addr][i].amount; if (_minimums[addr][i].gradual) { m = m.mul(_minimums[addr][i].endTime.sub(currentTime)).div(_minimums[addr][i].endTime.sub(_minimums[addr][i].startTime)); } minimum = minimum.add(m); } return minimum; }
0.8.7
// FUNCTIONS
function BOXToken() public { balances[msg.sender] = TOTAL_SUPPLY; totalSupply = TOTAL_SUPPLY; // do the distribution of the token, in token transfer transfer(WALLET_ECOSYSTEM, ALLOC_ECOSYSTEM); transfer(WALLET_FOUNDATION, ALLOC_FOUNDATION); transfer(WALLET_TEAM, ALLOC_TEAM); transfer(WALLET_PARTNER, ALLOC_PARTNER); transfer(WALLET_SALE, ALLOC_SALE); }
0.4.18
// get contributors' locked amount of token // this lockup will be released in 8 batches which take place every 180 days
function getLockedAmount_contributors(address _contributor) public constant returns (uint256) { uint256 countdownDate = contributors_countdownDate[_contributor]; uint256 lockedAmt = contributors_locked[_contributor]; if (now <= countdownDate + (180 * 1 days)) {return lockedAmt;} if (now <= countdownDate + (180 * 2 days)) {return lockedAmt.mul(7).div(8);} if (now <= countdownDate + (180 * 3 days)) {return lockedAmt.mul(6).div(8);} if (now <= countdownDate + (180 * 4 days)) {return lockedAmt.mul(5).div(8);} if (now <= countdownDate + (180 * 5 days)) {return lockedAmt.mul(4).div(8);} if (now <= countdownDate + (180 * 6 days)) {return lockedAmt.mul(3).div(8);} if (now <= countdownDate + (180 * 7 days)) {return lockedAmt.mul(2).div(8);} if (now <= countdownDate + (180 * 8 days)) {return lockedAmt.mul(1).div(8);} return 0; }
0.4.18
// get investors' locked amount of token // this lockup will be released in 3 batches: // 1. on delievery date // 2. three months after the delivery date // 3. six months after the delivery date
function getLockedAmount_investors(address _investor) public constant returns (uint256) { uint256 delieveryDate = investors_deliveryDate[_investor]; uint256 lockedAmt = investors_locked[_investor]; if (now <= delieveryDate) {return lockedAmt;} if (now <= delieveryDate + 90 days) {return lockedAmt.mul(2).div(3);} if (now <= delieveryDate + 180 days) {return lockedAmt.mul(1).div(3);} return 0; }
0.4.18
/** * @dev claims tokens from msg.sender to be converted to tokens on another blockchain * * @param _toBlockchain blockchain on which tokens will be issued * @param _to address to send the tokens to * @param _amount the amount of tokens to transfer */
function xTransfer(bytes32 _toBlockchain, bytes32 _to, uint256 _amount) public whenXTransfersEnabled { // get the current lock limit uint256 currentLockLimit = getCurrentLockLimit(); // require that; minLimit <= _amount <= currentLockLimit require(_amount >= minLimit && _amount <= currentLockLimit); lockTokens(_amount); // set the previous lock limit and block number prevLockLimit = currentLockLimit.sub(_amount); prevLockBlockNumber = block.number; // emit XTransfer event with id of 0 emit XTransfer(msg.sender, _toBlockchain, _to, _amount, 0); }
0.4.26
// used to transfer manually when senders are using BTC
function transferToAll(address[] memory tos, uint256[] memory values) public onlyOwner canTradable isActive { require( tos.length == values.length ); for(uint256 i = 0; i < tos.length; i++){ require(_icoSupply >= values[i]); totalNumberTokenSoldMainSale = totalNumberTokenSoldMainSale.add(values[i]); _icoSupply = _icoSupply.sub(values[i]); updateBalances(tos[i],values[i]); } }
0.5.3
/** * @dev gets x transfer amount by xTransferId (not txId) * * @param _xTransferId unique (if non zero) pre-determined id (unlike _txId which is determined after the transactions been broadcasted) * @param _for address corresponding to xTransferId * * @return amount that was sent in xTransfer corresponding to _xTransferId */
function getXTransferAmount(uint256 _xTransferId, address _for) public view returns (uint256) { // xTransferId -> txId -> Transaction Transaction storage transaction = transactions[transactionIds[_xTransferId]]; // verify that the xTransferId is for _for require(transaction.to == _for); return transaction.amount; }
0.4.26
/** * @dev private method to release tokens held by the contract * * @param _to the address to release tokens to * @param _amount the amount of tokens to release */
function releaseTokens(address _to, uint256 _amount) private { // get the current release limit uint256 currentReleaseLimit = getCurrentReleaseLimit(); require(_amount >= minLimit && _amount <= currentReleaseLimit); // update the previous release limit and block number prevReleaseLimit = currentReleaseLimit.sub(_amount); prevReleaseBlockNumber = block.number; // no need to require, reverts on failure token.transfer(_to, _amount); emit TokensRelease(_to, _amount); }
0.4.26
/** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */
function transfer(address _to, uint _value) public { uint codeLength; bytes memory empty; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if(role[msg.sender] == 2) { require(now >= projsealDate,"you can not transfer yet"); } if(role[msg.sender] == 3 || role[msg.sender] == 4) { require(now >= partnersealDate,"you can not transfer yet"); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength>0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } emit Transfer(msg.sender, _to, _value, empty); }
0.5.3
/** * @notice redeem tokens instantly * @param tokenAmount amount of token to redeem * @return true if success */
function instantRedemption(uint256 tokenAmount) external virtual override returns (bool) { require(tokenAmount > 0, "Token amount must be greater than 0"); uint256 requestDaiAmount = _cadOracle .cadToDai(tokenAmount.mul(_fixedPriceCADCent)) .div(100); require(requestDaiAmount <= fundsAvailable(), "Insufficient Dai for instant redemption"); _wToken.transferFrom(msg.sender, _poolSource, tokenAmount); _daiContract.transfer(msg.sender, requestDaiAmount); emit Redeemed(msg.sender, tokenAmount, requestDaiAmount); return true; }
0.6.8
/** * @notice set the expiry price in the oracle, can only be called by Bot address * @dev a roundId must be provided to confirm price validity, which is the first Chainlink price provided after the expiryTimestamp * @param _expiryTimestamp expiry to set a price for * @param _roundId the first roundId after expiryTimestamp */
function setExpiryPriceInOracle(uint256 _expiryTimestamp, uint80 _roundId) external { (, int256 price, , uint256 roundTimestamp, ) = aggregator.getRoundData(_roundId); require(_expiryTimestamp <= roundTimestamp, "ChainLinkPricer: roundId not first after expiry"); require(price >= 0, "ChainLinkPricer: invalid price"); if (msg.sender != bot) { bool isCorrectRoundId; uint80 previousRoundId = uint80(uint256(_roundId).sub(1)); while (!isCorrectRoundId) { (, , , uint256 previousRoundTimestamp, ) = aggregator.getRoundData(previousRoundId); if (previousRoundTimestamp == 0) { require(previousRoundId > 0, "ChainLinkPricer: Invalid previousRoundId"); previousRoundId = previousRoundId - 1; } else if (previousRoundTimestamp > _expiryTimestamp) { revert("ChainLinkPricer: previousRoundId not last before expiry"); } else { isCorrectRoundId = true; } } } oracle.setExpiryPrice(asset, _expiryTimestamp, uint256(price)); }
0.6.10
/** * @notice get the live price for the asset * @dev overides the getPrice function in OpynPricerInterface * @return price of the asset in USD, scaled by 1e8 */
function getPrice() external view override returns (uint256) { (, int256 answer, , , ) = aggregator.latestRoundData(); require(answer > 0, "ChainLinkPricer: price is lower than 0"); // chainlink's answer is already 1e8 return _scaleToBase(uint256(answer)); }
0.6.10
/** * @notice scale aggregator response to base decimals (1e8) * @param _price aggregator price * @return price scaled to 1e8 */
function _scaleToBase(uint256 _price) internal view returns (uint256) { if (aggregatorDecimals > BASE) { uint256 exp = aggregatorDecimals.sub(BASE); _price = _price.div(10**exp); } else if (aggregatorDecimals < BASE) { uint256 exp = BASE.sub(aggregatorDecimals); _price = _price.mul(10**exp); } return _price; }
0.6.10
/** * @notice redeem tokens asynchronously * @param tokenAmount amount of token to redeem * @return true if success */
function asyncRedemption(uint256 tokenAmount) external virtual override returns (bool) { require(tokenAmount >= 5e19, "Token amount must be greater than or equal to 50"); AsyncRedemptionRequest memory newRequest = AsyncRedemptionRequest(msg.sender, tokenAmount); _asyncRequests.push(newRequest); _wToken.transferFrom(msg.sender, address(this), tokenAmount); emit RedemptionPending(msg.sender, tokenAmount); return true; }
0.6.8
/** * @notice deposit Dai to faciliate redemptions * @param maxDaiAmount max amount of Dai to pay for redemptions * @return true if success */
function capitalize(uint256 maxDaiAmount) external returns (bool) { uint256 daiAmountRemaining = maxDaiAmount; uint256 newIndex = _asyncIndex; uint256 requestLength = _asyncRequests.length; for (; newIndex < requestLength; newIndex = newIndex.add(1)) { AsyncRedemptionRequest storage request = _asyncRequests[newIndex]; uint256 requestDaiAmount = _cadOracle .cadToDai(request.tokenAmount.mul(_fixedPriceCADCent)) .div(100); // if cannot completely redeem a request, then do not perform partial redemptions if (requestDaiAmount > daiAmountRemaining) { break; } daiAmountRemaining = daiAmountRemaining.sub(requestDaiAmount); _wToken.transfer(_poolSource, request.tokenAmount); _daiContract.transferFrom(msg.sender, request.account, requestDaiAmount); emit Redeemed(request.account, request.tokenAmount, requestDaiAmount); } // if all async requests have been redeemed, add Dai to this contract as reserve if (newIndex == requestLength && daiAmountRemaining > 0) { _daiContract.transferFrom(msg.sender, address(this), daiAmountRemaining); emit Capitalized(daiAmountRemaining); } // update redemption index to the latest _asyncIndex = newIndex; return true; }
0.6.8
/** * @notice see the total token balance awaiting redemptions for a given account * @dev IMPORTANT this function involves unbounded loop, should NOT be used in critical logical paths * @param account account that has tokens pending * @return token amount in 18 decimals */
function tokensPending(address account) external view virtual override returns (uint256) { uint256 pendingAmount = 0; uint256 requestLength = _asyncRequests.length; for (uint256 i = _asyncIndex; i < requestLength; i = i.add(1)) { AsyncRedemptionRequest storage request = _asyncRequests[i]; if (request.account == account) { pendingAmount = pendingAmount.add(request.tokenAmount); } } return pendingAmount; }
0.6.8
//gives appropriate number of tokens to purchasing address
function purchaseTokens(address payable playerAddress, uint256 etherValue) //checks if purchase allowed -- only relevant for limiting actions during setup phase purchaseAllowed( etherValue ) internal returns( uint256 ) { //calculates fee/rewards uint[2] memory feeAndValue = valueAfterFee( etherValue ); //calculates tokens from postFee value of input ether uint256 amountTokens = etherToTokens( feeAndValue[1] ); //avoid overflow errors require ( ( (amountTokens + totalSupply) > totalSupply), "purchase would cause integer overflow" ); // send rewards to partner contract, to be distributed to its holders address payable buddy = partnerAddress_; ( bool success, bytes memory returnData ) = buddy.call.value( feeAndValue[0] )(""); require( success, "failed to send funds to partner contract (not enough gas provided?)" ); //adds new tokens to total token supply and gives them to the player //also updates reward tracker (payoutsToLedger_) for player address mint( playerAddress, amountTokens ); return( amountTokens ); }
0.5.12
// |--------------------------------------| // [20, 30, 40, 50, 60, 70, 80, 99999999] // Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 result = 0; if (_from < START_BLOCK) return 0; for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) { uint256 endBlock = HALVING_AT_BLOCK[i]; if (_to <= endBlock) { uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]); return result.add(m); } if (_from < endBlock) { uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]); _from = endBlock; result = result.add(m); } } return result; }
0.6.12
// lock 75% of reward if it come from bounus time
function _harvest(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accyodaPerShare).div(1e12).sub(user.rewardDebt); uint256 masterBal = yoda.balanceOf(address(this)); if (pending > masterBal) { pending = masterBal; } if(pending > 0) { yoda.transfer(msg.sender, pending); uint256 lockAmount = 0; if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) { lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100); yoda.lock(msg.sender, lockAmount); } user.rewardDebtAtBlock = block.number; emit SendyodaReward(msg.sender, _pid, pending, lockAmount); } user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); } }
0.6.12
// Deposit LP tokens to yodaMasterFarmer for yoda allocation.
function deposit(uint256 _pid, uint256 _amount) public { require(_amount > 0, "yodaMasterFarmer::deposit: amount must be greater than 0"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); _harvest(_pid); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (user.amount == 0) { user.rewardDebtAtBlock = block.number; } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); }
0.6.12
// Withdraw LP tokens from yodaMasterFarmer.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "yodaMasterFarmer::withdraw: not good"); updatePool(_pid); _harvest(_pid); if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
0.6.12
// Claim rewards for Bunnies
function claimRewards(address _contractAddress) public { uint256 numStaked = TokensOfOwner[_contractAddress][msg.sender].length; if (numStaked > 0) { uint256 rRate = RewardRate[_contractAddress] * numStaked; uint256 reward = rRate * ((block.timestamp - lastClaim[_contractAddress][msg.sender]) / 86400); if (reward > 0) { lastClaim[_contractAddress][msg.sender] = uint80(block.timestamp); IRBCUtility(UtilityAddress).getReward(msg.sender, reward); } } }
0.8.7
// Stake Bunni (deposit ERC721)
function deposit(address _contractAddress, uint256[] calldata tokenIds) external whenNotPaused { require(RewardRate[_contractAddress] > 0, "invalid address for staking"); claimRewards(_contractAddress); //Claims All Rewards uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { IERC721(_contractAddress).transferFrom(msg.sender, address(this), tokenIds[i]); TokensOfOwner[_contractAddress][msg.sender].push(tokenIds[i]); } lastClaim[_contractAddress][msg.sender] = uint80(block.timestamp); }
0.8.7
// Unstake Bunni (withdrawal ERC721)
function withdraw(address _contractAddress, uint256[] calldata tokenIds, bool _doClaim) external nonReentrant() { if (_doClaim) //You can Withdraw without Claiming if needs be { claimRewards(_contractAddress); //Claims All Rewards } uint256 length = tokenIds.length; for (uint256 i; i < length; i++) { require(amOwnerOf(_contractAddress, tokenIds[i]), "Bunni not yours"); IERC721(_contractAddress).transferFrom(address(this), msg.sender, tokenIds[i]); TokensOfOwner[_contractAddress][msg.sender] = _moveTokenInTheList(TokensOfOwner[_contractAddress][msg.sender], tokenIds[i]); TokensOfOwner[_contractAddress][msg.sender].pop(); if (TokensOfOwner[_contractAddress][msg.sender].length < 1) //<= 0 { delete(lastClaim[_contractAddress][msg.sender]); } } }
0.8.7
// Returns the current rate of rewards per token (doh)
function rewardPerToken() public view returns (uint256) { // Do not distribute rewards before games begin if (block.timestamp < startTime) { return 0; } if (_totalSupply == 0) { return rewardPerTokenStored; } // Effective total supply takes into account all the multipliers bought. uint256 effectiveTotalSupply = _totalSupply.add(_totalSupplyAccounting); return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(effectiveTotalSupply)); }
0.6.12
// Returns the current reward tokens that the user can claim.
function earned(address account) public view returns (uint256) { // Each user has it's own effective balance which is just the staked balance multiplied by boost level multiplier. uint256 effectiveBalance = _balances[account].add(_balancesAccounting[account]); return effectiveBalance.mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); }
0.6.12
// Withdraw function to remove stake from the pool
function withdraw(uint256 amount) public override { require(amount > 0, "Cannot withdraw 0"); updateReward(msg.sender); uint256 tax = amount.mul(devFee).div(1000); stakingToken.safeTransfer(devFund, tax); stakingToken.safeTransfer(msg.sender, amount.sub(tax)); super.withdraw(amount); uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender); adjustEffectiveStake(msg.sender, userTotalMultiplier, true); emit Withdrawn(msg.sender, amount); }
0.6.12
// Called to start the pool with the reward amount it should distribute // The reward period will be the duration of the pool.
function notifyRewardAmount(uint256 reward) external onlyOwner { rewardToken.safeTransferFrom(msg.sender, address(this), reward); updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); }
0.6.12
// Notify the reward amount without updating time;
function notifyRewardAmountWithoutUpdateTime(uint256 reward) external onlyOwner { updateRewardPerTokenStored(); if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } emit RewardAdded(reward); }
0.6.12
// Calculate the cost for purchasing a boost.
function calculateCost( address _user, address _token, uint256 _level ) public view returns (uint256) { uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), _token, _user); if (lastLevel > _level) return 0; return deflector.getSpendableCostPerTokenForUser(address(this), _user, _token, _level); }
0.6.12
// Purchase a multiplier level, same level cannot be purchased twice.
function purchase(address _token, uint256 _level) external { require(deflector.isSpendableTokenInContract(address(this), _token), "Not a multiplier token"); uint256 lastLevel = deflector.getLastTokenLevelForUser(address(this), msg.sender, _token); require(lastLevel < _level, "Cannot downgrade level or same level"); uint256 cost = calculateCost(msg.sender, _token, _level); IERC20(_token).safeTransferFrom(msg.sender, devFund, cost); // Update balances and level in the multiplier contarct deflector.purchase(address(this), msg.sender, _token, _level); // Adjust new level uint256 userTotalMultiplier = deflector.getTotalValueForUser(address(this), msg.sender); adjustEffectiveStake(msg.sender, userTotalMultiplier, false); emit Boost(_token, _level); }
0.6.12
// constructor called during creation of contract
function FuBi() { owner = msg.sender; // person who deploy the contract will be the owner of the contract balances[owner] = totalSupply; // balance of owner will be equal to 20000 million }
0.4.25
// send _amount to each address
function multiSend(address[] _addrs, uint _amount) external payable { require(_amount > 0); uint _totalToSend = _amount.mul(_addrs.length); require(msg.value >= _totalToSend); // try sending to multiple addresses uint _totalSent = 0; for (uint256 i = 0; i < _addrs.length; i++) { require(_addrs[i] != address(0)); if (_addrs[i].send(_amount)) { _totalSent = _totalSent.add(_amount); // emit Send(_addrs[i], _amount); } else { emit Fail(_addrs[i], _amount); } } // refund unsent ether if (msg.value > _totalSent) { msg.sender.transfer(msg.value.sub(_totalSent)); // emit Send(msg.sender, msg.value.sub(_totalSent)); } }
0.4.21
/** * Set basic quarter details for Chainlink Receiver * @param alpha_token_contract IKladeDiffToken - Klade Alpha Token Contract * @param omega_token_contract IKladeDifFToken - Klade Omega Token Contract * @param chainlink_diff_oracle IChainlinkOracle - Chainlink oracle contract that provides difficulty information * @param chainlink_blocknum_oracle IChainlinkOracle - Chainlink oracle contract that provides difficulty information * @param required_collateral uint - required collateral to mint a single pair of Klade Alpha/Omega tokens * @param hedged_revenue uint - hedged revenue for bitcoin miners for single pair of tokens * @param miner_earnings uint - miner earnings for single pair of tokens */
function set_quarter_details( IKladeDiffToken alpha_token_contract, IKladeDiffToken omega_token_contract, IChainlinkOracle chainlink_diff_oracle, IChainlinkOracle chainlink_blocknum_oracle, uint256 required_collateral, uint256 hedged_revenue, uint256 miner_earnings ) external { require( msg.sender == KladeAddress1 || msg.sender == KladeAddress2, "Only Klade can set quarter details" ); require(Q3_set == false, "Quarter details already set"); Q3_details = quarter_details( alpha_token_contract, omega_token_contract, chainlink_diff_oracle, chainlink_blocknum_oracle, required_collateral, hedged_revenue, Q3_end_unix, miner_earnings, 0 ); Q3_set = true; }
0.7.3