comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * At the call to getChainlinkUpdate at the beginning or end of the quarter, the current_block_number should * be passed in as the block number at the beginning or end of the quarter. * On all other calls, current_block_number should be fed as the block number * at the most recent time the Oracle has updated...
function getChainlinkUpdate() external returns (bool updated) { require(Q3_set, "Quarter details not set yet"); uint256 i = Q3_details.number_of_updates; require(i < 13, "All datapoints for the quarter have been collected"); ChainlinkUpdate memory current_update = read...
0.7.3
/** * Checks if the current_update has updated difficulty and block_number values * compared to last_update. If either the difficulty or the block_number has * not been updated by Chainlink, this returns false. * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle * @param c...
function new_chainlink_data( ChainlinkUpdate memory last_update, ChainlinkUpdate memory current_update ) internal pure returns (bool new_data) { bool new_difficulty_data = current_update.diff_roundID != last_update.diff_roundID; bool new_blocknum_data = ...
0.7.3
/** * Calls Chainlink's Oracles, gets the latest data, and returns it. * @param blocknum_oracle IChainlinkOracle - Chainlink block number oracle * @param diff_oracle IChainlinkOracle - Chainlink difficulty number oracle */
function read_chainlink( IChainlinkOracle blocknum_oracle, IChainlinkOracle diff_oracle ) internal view returns (ChainlinkUpdate memory latest) { uint80 updated_roundID_diff; int256 current_diff; uint256 startedAt; uint256 updatedAt; uint80 answeredInR...
0.7.3
/** * Revenue (in WBTC base units) for 10 TH/s over the blocks from startBlock to endBlock * does not account for if there is a halving in between a difficulty update. * should not be relevant for Q3 2021 * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle * @param current...
function additional_miner_earnings( ChainlinkUpdate memory last_update, ChainlinkUpdate memory current_update ) internal view returns (uint256 earnings) { uint256 startBlock = last_update.block_number; uint256 startDiff = last_update.difficulty; uint256 endBlock = curre...
0.7.3
/** * Check that the values that are trying to be added to the ChainlinkData * for a quarter actually makes sense. * Returns True if the update seems reasonable and returns false if the update * values seems unreasonable * Very generous constraints that are just sanity checks. * @param update ChainlinkUpd...
function check_reasonable_values(ChainlinkUpdate memory update) internal view returns (bool reasonable) { uint256 update_diff = update.difficulty; uint256 update_block_number = update.block_number; uint256 number_of_updates = Q3_details.number_of_updates; ...
0.7.3
// payouts are set in WBTC base units for 1.0 tokens
function set_payouts() public { require( Q3_details.number_of_updates == 13, "Need 13 datapoints before setting payout" ); require( (block.timestamp >= Q3_details.end_unix), "You cannot set a payout yet" ); uint256 hedged...
0.7.3
// If any address accidentally sends any ERC20 token to this address, // they can contact us. Off-chain we will verify that the address did // in fact accidentally send tokens and return them.
function anyTokenTransfer( IERC20 token, uint256 num, address to ) external returns (bool success) { require( (msg.sender == KladeAddress1 || msg.sender == KladeAddress2), "Only Klade can recover tokens" ); return token.transfer(to, nu...
0.7.3
/** * @dev Migrate a users' entire balance * * One way function. SAFE1 tokens are BURNED. SAFE2 tokens are minted. */
function migrate() external { require(block.timestamp >= startTime, "SAFE2 migration has not started"); require(block.timestamp < startTime + migrationDuration, "SAFE2 migration has ended"); // Current balance of SAFE for user. uint256 safeBalance = SAFE(safe).balanceOf(_msgSender(...
0.6.12
//utility for calculating (approximate) square roots. simple implementation of Babylonian method //see: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
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; } }
0.5.12
//user buys token with ETH
function buy() payable { if(sellsTokens || msg.sender == owner) { uint order = msg.value / sellPrice; uint can_sell = ERC20(asset).balanceOf(address(this)) / units; if(order > can_sell) { uint256 change = msg.value - (can_sell ...
0.4.11
// called once by the factory at time of deployment
function initialize( address _pair, uint256 _unstakingFrozenTime, address _rewardFund, address _timelock ) external override { require(_initialized == false, "StakePool: Initialize must be false."); require(unstakingFrozenTime <= 30 days, "StakePool: unstakingF...
0.7.6
//insert new investor
function insert(address addr, uint value) public returns (bool) { uint keyIndex = d.investors[addr].keyIndex; if (keyIndex != 0) return false; d.investors[addr].value = value; keyIndex = d.keys.length++; d.investors[addr].keyIndex = keyIndex; d.keys[keyIndex] = add...
0.4.25
//functions is calling when transfer money to address of this contract
function() public payable { // investor get him dividends when send value = 0 to address of this contract if (msg.value == 0) { getDividends(); return; } // getting referral address from data of request address a = msg.data.toAddr(); //call invest...
0.4.25
// private function for get dividends
function _getMydividends(bool withoutThrow) private { // get investor info Storage.investor memory investor = getMemInvestor(msg.sender); //check if investor exists if(investor.keyIndex <= 0){ if(withoutThrow){ return; } revert("sender...
0.4.25
/** * @notice Enables any address to set the strike price for an associated LSP. * @param longShortPair address of the LSP. * @param strikePrice the strike price for the covered call for the associated LSP. * @param basePercentage the base percentage of collateral per pair paid out to long tokens, expressed * with...
function setLongShortPairParameters( address longShortPair, uint256 strikePrice, uint256 basePercentage ) public nonReentrant() { require(ExpiringContractInterface(longShortPair).expirationTimestamp() != 0, "Invalid LSP address"); SuccessTokenLongShortPairParameters memory pa...
0.8.9
/** * @dev Settle the bid for the swap pair. */
function FeswaPairSettle(uint256 tokenID) external { require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing FeswaPair storage pairInfo = ListPools[tokenID]; if(pairInfo.poolState == PoolRunningPhase.BidPhase){ req...
0.7.0
/** * @dev Sell the Pair with the specified Price. */
function FeswaPairForSale(uint256 tokenID, uint256 pairPrice) external returns (uint256 newPrice) { require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing FeswaPair storage pairInfo = ListPools[tokenID]; require(pairInfo.poolS...
0.7.0
/** * @dev Return the token-pair information */
function getPoolInfoByTokens(address tokenA, address tokenB) external view returns (uint256 tokenID, address nftOwner, FeswaPair memory pairInfo) { (address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA); tokenID = uint256(keccak256(abi.encodePacked(address(this), to...
0.7.0
/* * main function for receiving the ETH from the investors * and transferring tokens after calculating the price */
function buyTokens(address _buyer, uint256 _value) internal { // prevent transfer to 0x0 address require(_buyer != 0x0); // msg value should be more than 0 require(_value > 0); // total tokens equal price is multiplied by the ether value provided ...
0.4.24
/** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime crowdsale opening time * @param _closingTime crowdsale closing time * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _remainingTokens...
function DagtCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, address _remainingTokensWallet, uint256 _cap, uint _lockingRatio, MintableToken _token) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) ...
0.4.21
/** * * @dev Computes bonus based on time of contribution relative to the beginning of crowdsale * @return bonus */
function computeTimeBonus(uint256 _time) public constant returns(uint256) { require(_time >= openingTime); for (uint i = 0; i < BONUS_TIMES.length; i++) { if (_time.sub(openingTime) <= BONUS_TIMES[i]) { return BONUS_TIMES_VALUES[i]; } } re...
0.4.21
/** * @dev Sets bonuses for time */
function setBonusesForTimes(uint32[] times, uint32[] values) public onlyOwner { require(times.length == values.length); for (uint i = 0; i + 1 < times.length; i++) { require(times[i] < times[i+1]); } BONUS_TIMES = times; BONUS_TIMES_VALUES = values; }
0.4.21
/** * @dev Sets bonuses for USD amounts */
function setBonusesForAmounts(uint256[] amounts, uint32[] values) public onlyOwner { require(amounts.length == values.length); for (uint i = 0; i + 1 < amounts.length; i++) { require(amounts[i] > amounts[i+1]); } BONUS_AMOUNTS = amounts; BONUS_AMOUNTS_VALUES =...
0.4.21
/** * @dev Sets the provided edition to either a deactivated state or reduces the available supply to zero * @dev Only callable from edition artists defined in KODA NFT contract * @dev Only callable when contract is not paused * @dev Reverts if edition is invalid * @dev Reverts if edition is not active in KDO...
function deactivateOrReduceEditionSupply(uint256 _editionNumber) external whenNotPaused { (address artistAccount, uint256 _) = kodaAddress.artistCommission(_editionNumber); require(msg.sender == artistAccount || msg.sender == owner, "Only from the edition artist account"); // only allow them to be disa...
0.4.24
/// @dev Purchase with token private sales fn /// Requires: 1. token amount to transfer, /// @param editions number of editions to purchase (needs to have same tokens)
function purchaseWithTokens(uint256 editions) public nonReentrant { require(numberSoldPrivate + editions <= numberPrivateSale, "No sale"); require(editions > 0, "Min 1"); // Attempt to transfer tokens for mint try privateSaleToken.transferFrom( msg.sender, ...
0.8.6
/** * @notice Award from airdrop * @param _id Airdrop id * @param _recipient Recepient of award * @param _amount0 The token0 amount * @param _amount1 The token1 amount * @param _proof Merkle proof to correspond to data supplied */
function award(uint _id, address _recipient, uint256 _amount0, uint256 _amount1, bytes32[] calldata _proof) public { Airdrop storage airdrop = airdrops[_id]; bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0, _amount1)); require( validate(airdrop.root, _proof, hash), "Invalid p...
0.8.1
/** * @notice Award from multiple airdrops to single recipient * @param _ids Airdrop ids * @param _recipient Recepient of award * @param _amount0s The token0 amounts * @param _amount1s The token1 amounts * @param _proofs Merkle proofs */
function awardFromMany(uint[] calldata _ids, address _recipient, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public { uint totalAmount0; uint totalAmount1; for (uint i = 0; i < _ids.length; i++) { uint id = _ids[i]; bytes...
0.8.1
/** * @notice Award from airdrop to multiple recipients * @param _id Airdrop ids * @param _recipients Recepients of award * @param _amount0s The karma amount * @param _amount1s The currency amount * @param _proofs Merkle proofs */
function awardToMany(uint _id, address[] calldata _recipients, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public { for (uint i = 0; i < _recipients.length; i++) { address recipient = _recipients[i]; if( airdrops[_id].awarded[recipient] ) ...
0.8.1
/** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete * @param pid - number of the pool from which the funds are withdrawn */
function completeWithdrawals(address[] memory userList, uint256 pid) external onlyOwner startedPool(pid) { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = poolInfo[pid].strategy; address user; PendingWi...
0.8.12
// the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) { // if we reach this point successfully, it means that the attached authenticity proof has passed! if (msg.sender != oraclize_cbAddress()) throw; if(queryIdToIsEthPrice[_queryId]){ eth_price = parseInt(_r...
0.4.20
/// @dev Initialize new contract /// @param _key the resolver key for this contract /// @return _success if the initialization is successful
function init(bytes32 _key, address _resolver) internal returns (bool _success) { bool _is_locked = ContractResolver(_resolver).locked_forever(); if (_is_locked == false) { CONTRACT_ADDRESS = address(this); resolver = _resolver; key = _key; require(Contra...
0.4.25
/** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit * @param pid - number of the pool to which the deposit goes */
function deposit(uint256[3] memory amounts, uint256 pid) external whenNotPaused startedPool(pid) returns (uint256) { IStrategy strategy = poolInfo[pid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if...
0.8.12
/** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive * @param pid - number of the pool from which the funds are withdrawn */
function withdraw( uint256 lpShares, uint256[3] memory minAmounts, uint256 pid ) external whenNotPaused startedPool(pid) { IStrategy strategy = poolInfo[pid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP ba...
0.8.12
/** @notice Check if a certain address is whitelisted to read sensitive information in the storage layer @dev if the address is an account, it is allowed to read. If the address is a contract, it has to be in the whitelist */
function senderIsAllowedToRead() internal view returns (bool _senderIsAllowedToRead) { // msg.sender is allowed to read only if its an EOA or a whitelisted contract _senderIsAllowedToRead = (msg.sender == tx.origin) || daoWhitelistingStorage().whitelist(msg.sender); ...
0.4.25
/** @notice Calculate the start of a specific milestone of a specific proposal. @dev This is calculated from the voting start of the voting round preceding the milestone This would throw if the voting start is 0 (the voting round has not started yet) Note that if the milestoneIndex is exactly the same as the nu...
function startOfMilestone(bytes32 _proposalId, uint256 _milestoneIndex) internal view returns (uint256 _milestoneStart) { uint256 _startOfPrecedingVotingRound = daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex); require(_startOfPrecedingVotingRound > 0);...
0.4.25
/** @notice Calculate the actual voting start for a voting round, given the tentative start @dev The tentative start is the ideal start. For example, when a proposer finish a milestone, it should be now However, sometimes the tentative start is too close to the end of the quarter, hence, the actual voting start s...
function getTimelineForNextVote( uint256 _index, uint256 _tentativeVotingStart ) internal view returns (uint256 _actualVotingStart) { uint256 _timeLeftInQuarter = getTimeLeftInQuarter(_tentativeVotingStart); uint256 _votingDuration = getUintConfig...
0.4.25
/** @notice Migrate this DAO to a new DAO contract @dev This is the second step of the 2-step migration Migration can only be done during the locking phase, after the global rewards for current quarter are set. This is to make sure that there is no rewards calculation pending before the DAO is migrated to new c...
function migrateToNewDao( address _newDaoContract, address _newDaoFundingManager, address _newDaoRewardsManager ) public if_root() ifGlobalRewardsSet(currentQuarterNumber()) { require(isLockingPhase()); require(daoUpgradeStorage().isRepla...
0.4.25
/** @notice Submit a new preliminary idea / Pre-proposal @dev The proposer has to send in a collateral == getUintConfig(CONFIG_PREPROPOSAL_COLLATERAL) which he could claim back in these scenarios: - Before the proposal is finalized, by calling closeProposal() - After all milestones are done and the final voti...
function submitPreproposal( bytes32 _docIpfsHash, uint256[] _milestonesFundings, uint256 _finalReward ) external payable { senderCanDoProposerOperations(); bool _isFounder = is_founder(); require(MathHelper.sumNumbers(_milestonesFunding...
0.4.25
/** @notice Modify a proposal (this can be done only before setting the final version) @param _proposalId Proposal ID (hash of IPFS doc of the first version of the proposal) @param _docIpfsHash Hash of IPFS doc of the modified version of the proposal @param _milestonesFundings Array of fundings of the modified ...
function modifyProposal( bytes32 _proposalId, bytes32 _docIpfsHash, uint256[] _milestonesFundings, uint256 _finalReward ) external { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); require(isEditable(_proposalId))...
0.4.25
/** @notice Finalize a proposal @dev After finalizing a proposal, no more proposal version can be added. Proposer will only be able to change fundings and add more docs Right after finalizing a proposal, the draft voting round starts. The proposer would also not be able to closeProposal() anymore (hence, cannot...
function finalizeProposal(bytes32 _proposalId) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); require(isEditable(_proposalId)); checkNonDigixProposalLimit(_proposalId); // make sure we have reasonably enough time left in the q...
0.4.25
/** @notice Function to set milestone to be completed @dev This can only be called in the Main Phase of DigixDAO by the proposer. It sets the voting time for the next milestone, which is immediately, for most of the times. If there is not enough time left in the current quarter, then the next voting is postpone...
function finishMilestone(bytes32 _proposalId, uint256 _milestoneIndex) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); uint256[] memory _currentFundings; (_currentFundings,) = daoStorage().readProposalFunding(_proposalId); //...
0.4.25
/** @notice Function to update the PRL (regulatory status) status of a proposal @dev if a proposal is paused or stopped, the proposer wont be able to withdraw the funding @param _proposalId ID of the proposal @param _doc hash of IPFS uploaded document, containing details of PRL Action */
function updatePRL( bytes32 _proposalId, uint256 _action, bytes32 _doc ) public if_prl() { require(_action == PRL_ACTION_STOP || _action == PRL_ACTION_PAUSE || _action == PRL_ACTION_UNPAUSE); daoStorage().updateProposalPRL(_proposalId, _action, _d...
0.4.25
/** @notice Function to close proposal (also get back collateral) @dev Can only be closed if the proposal has not been finalized yet @param _proposalId ID of the proposal */
function closeProposal(bytes32 _proposalId) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); bytes32 _finalVersion; bytes32 _status; (,,,_status,,,,_finalVersion,,) = daoStorage().readProposal(_proposalId); require(_final...
0.4.25
/** @notice Function for founders to close all the dead proposals @dev Dead proposals = all proposals who are not yet finalized, and been there for more than the threshold time The proposers of dead proposals will not get the collateral back @param _proposalIds Array of proposal IDs */
function founderCloseProposals(bytes32[] _proposalIds) external if_founder() { uint256 _length = _proposalIds.length; uint256 _timeCreated; bytes32 _finalVersion; bytes32 _currentState; for (uint256 _i = 0; _i < _length; _i++) { (,,,_curre...
0.4.25
/** * @dev Execute multiple trades in a single transaction. * @param wrappers Addresses of exchange wrappers. * @param token Address of ERC20 token to receive in first trade. * @param trade1 Calldata of Ether => ERC20 trade. * @param trade2 Calldata of ERC20 => Ether trade. */
function trade( address[2] wrappers, address token, bytes trade1, bytes trade2 ) external payable { // Execute the first trade to get tokens require(execute(wrappers[0], msg.value, trade1)); uint256 tokenBalance = IERC20(token)...
0.4.24
/** * @dev Transfer function to assign a token to another address * Reverts if the address already owns a token * @param from address the address that currently owns the token * @param to address the address to assign the token to * @param tokenId uint256 ID of the token to transfer */
function transferFrom( address from, address to, uint256 tokenId ) public isValidAddress(to) isValidAddress(from) onlyOwner { require(tokenOwned[to] == 0, "Destination address already owns a token"); require(ownerOf[tokenId] == from, "From address does not own token"); ...
0.5.17
/** * @dev Burn function to remove a given tokenId * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to burn */
function burn(uint256 tokenId) public onlyOwner { address previousOwner = ownerOf[tokenId]; require(previousOwner != address(0), "ERC721: token does not exist"); delete tokenOwned[previousOwner]; delete ownerOf[tokenId]; for (uint256 i = 0; i < tokens.length; i++) { ...
0.5.17
/// @notice The actual mint function used for presale and public minting then. /// @param amount The number of tokens you're able to mint in one transaction.
function mint(uint256 amount) external payable { require(!saleIsClosed, "The sale is closed."); require(amount > 0 && amount <= 3, "Amount must be within [1;3]."); if(whitelistSaleIsActive){ // check if we are in presale require(hasRole(WHITELIST_ROLE, msg.sender), "You're not on t...
0.8.4
/// @notice Admin mint function that is used for preminting NFTs. /// @param amount The amount of NFTs that can be minted in one transaction.
function adminMint(address receiver, uint256 amount) external onlyOwner{ require(!saleIsClosed, "The sale is closed."); require(_tokenIdReserveCounter.current() < MAX_RESERVE , "Out of reserve tokens."); require(amount > 0 && amount <= 20, "Amount must be within [1;20]."); for(uint256 i...
0.8.4
/// @dev claim tokenId mints with placeholder URI in batch 'phase'
function safeMint() external payable nonReentrant { // check mint is open require(mintOpen, 'CLOSED'); // check whitelist, if flipped on if (whitelistOn) require(whitelist[msg.sender], 'NOT_WHITELISTED'); // check if price attached require(msg.value == mintPrice, 'B...
0.8.10
/// **** MINT MGMT /// @dev set next phase for minting (limit + price)
function setMintPhase(uint256 mintPhaseLimit_, uint256 mintPrice_) external onlyOwner { // ensure Id limit doesn't exceed cap require(mintPhaseLimit_ <= mintCap, 'CAPPED'); // ensure Id limit is greater than current supply (increasing phase) require(mintPhaseLimit_ > totalSupply(), '...
0.8.10
/// @dev update minted URIs
function setURIs(uint256[] calldata tokenIds, string[] calldata uris) external onlyOwner { require(tokenIds.length == uris.length, 'NO_ARRAY_PARITY'); // this is reasonably safe from overflow because incrementing `i` loop beyond // 'type(uint256).max' is exceedingly unlikely compared to opt...
0.8.10
/// @dev ETH tranfer helper - optimized in assembly:
function _safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // transfer the ETH and store if it succeeded or not callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, 'ETH_TRANSFER_FAILED'); }
0.8.10
/** * @dev Reserved for giveaways. */
function reserveGiveaway(uint256 numTokens) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply() + numTokens <= 10, "10 mints for sale giveaways"); uint256 index; // Reserved for people who helped this project and giveaways for (index = 0; index < numToken...
0.7.6
/* * - `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"); uint256 senderBalance = _balances[sender]; require...
0.8.0
// Purchase tokens
function buyTokens(address beneficiary) public nonReentrant payable whenNotPaused { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnWeiAmount; // calculate token amount to be created uint rate = getRate(); as...
0.5.11
/** * @dev Bootstrap the supply distribution and fund the UniswapV2 liquidity pool */
function bootstrap() external returns (bool){ require(isBootStrapped == false, 'Require unintialized token'); require(msg.sender == owner, 'Require ownership'); //Distribute tokens uint256 premineAmount = 100000000 * (10 ** 18); //100 mil uint256 marketingAmount = 1000000000 * ...
0.6.2
// the function is name differently to not cause inheritance clash in truffle and allows tests
function initializeVault(address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) public initializer { require(_toInvestNumerator <= _toInvestDenominator, "cannot invest more than 100%"); require(_toInvestDenominator != 0, "cannot divi...
0.5.16
//Get the tokens that exist for this wallet
function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); ...
0.8.0
// if any applicable tokens are held by this contract, it should be able to deposit them
function _depositAssets () internal { uint LPBalance = IERC20(liquidity).balanceOf(address(this)); // load LP balance into memory if(LPBalance > 0) // are there any LP tokens? IStakingRewards(staking).deposit(LPBalance); ...
0.8.7
// claim rewards from NFTs, staking, and cKRILL position
function _claimRewardsAndDisburse() internal { IClaimable(staking).claim(); // Claim rewards from the LP staking contract IClaimable(whalesGame).claim(); // Claim rewards from the whales game contract if(ICompounder(cKrill).dividendsOf(address(this)) > 0) // If this contract ha...
0.8.7
// Callback function, distribute tokens to sender when ETH donation is recieved
function () payable public { require(isLive); uint256 donation = msg.value; uint256 amountZNT = donation * rateOfZNT; uint256 amountZLT = donation * rateOfZLT; require(availableZNT >= amountZNT && availableZLT >= amountZLT); donationOf[msg.sender] += donat...
0.4.24
/** * @dev Resets the player's current progress. */
function resetProgress() public returns (bool) { if (playerCurrentProgress[msg.sender] > 0) { playerCurrentProgress[msg.sender] = 0; playerAddressToBid[msg.sender] = 0; p...
0.4.24
/** * @dev Calculates the payout based on roll under in Wei. */
function _calculatePayout( uint256 rollUnder, uint256 value) internal view isWithinLimits(value) returns (uint256) { require(rollUnder >= minRoll && rollUnder <= maxRoll, "invalid roll under number!"); uint256 _t...
0.4.24
/* at initialization, setup the owner */
function WowanderICOPrivateCrowdSale( address addressOfTokenUsedAsReward, address addressOfBeneficiary ) public { beneficiary = addressOfBeneficiary; //startTime = 1516021200; startTime = 1516021200 - 3600 * 24; // TODO remove duration = 744 hours; tokensCont...
0.4.18
/** * @dev Transfer several token for a specified addresses * @param _to The array of addresses to transfer to. * @param _value The array of amounts to be transferred. */
function massTransfer(address[] memory _to, uint[] memory _value) public returns (bool){ require(_to.length == _value.length, "You have different amount of addresses and amounts"); uint len = _to.length; for(uint i = 0; i < len; i++){ if(!_transfer(_to[i], _value[i])){ ...
0.5.12
/** * @dev Emit new tokens and transfer from 0 to client address. This function will generate 21.5% of tokens for management address as well. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function _mint(address _to, uint _value) private returns (bool){ require(_to != address(0), "Receiver address cannot be null"); require(_to != address(this), "Receiver address cannot be ITCM contract address"); require(_value > 0 && _value <= leftToMint, "Looks like we are unable to mint such...
0.5.12
/** * @dev This is wrapper for _mint. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function mint(address _to, uint _value) public returns (bool){ require(msg.sender != address(0), "Sender address cannon be null"); require(msg.sender == mintingAllowedForAddr || mintingAllowedForAddr == address(0) && msg.sender == contractCreator, "You are unavailable to mint tokens"); retu...
0.5.12
/** * @dev Similar to mint function but take array of addresses and values. * @param _to The addresses to transfer to. * @param _value The amounts to be transferred. */
function mint(address[] memory _to, uint[] memory _value) public returns (bool){ require(_to.length == _value.length, "You have different amount of addresses and amounts"); require(msg.sender != address(0), "Sender address cannon be null"); require(msg.sender == mintingAllowedForAddr || minti...
0.5.12
/** * @dev Set a contract address that allowed to mint tokens. * @param _address The address of another contract. */
function setMintingContractAddress(address _address) public returns (bool){ require(mintingAllowedForAddr == address(0) && msg.sender == contractCreator, "Only contract creator can set minting contract and only when it is not set"); mintingAllowedForAddr = _address; return true; }
0.5.12
// Guards against integer overflows
function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 c = a * b; assert(c / a == b); return c; } }
0.5.17
/** * @dev this function will send the Team tokens to given address * @param _teamAddress ,address of the bounty receiver. * @param _value , number of tokens to be sent. */
function sendTeamTokens(address _teamAddress, uint256 _value) external whenNotPaused onlyOwner returns (bool) { require(teamTokens >= _value); totalReleased = totalReleased.add(_value); require(totalReleased <= totalSupply()); teamTokens = teamTokens.sub(_value); teamToken...
0.5.0
/** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */
function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmoun...
0.8.3
/** * @dev Get withdraw amount of shares value * @param shares How many shares will be exchanged */
function getWithdrawAmount(uint256 shares, address _addr) public view returns (uint256 amount) { uint256 PPS; //check if last user: cannot use shares, could be partial withdraw uint256 userShareBalance = balanceOf(_addr); if (userShareBalance == to...
0.8.3
/** * @dev Get mint amount for roll() * @param timestamp current timestamp */
function getMintAmount(uint timestamp) public view returns (uint256 amount) { if (timestamp < deployTime + 31557600) { amount = am1 ; } else { if (timestamp < deployTime + 63115200) { amount = am2 ; } else { if (timestamp < dep...
0.8.3
/* * @notice Rolls the vault's funds into a new short position. */
function roll() external onlyOwner { require(block.timestamp >= readyAt, "not ready to roll yet"); uint mintAmount = getMintAmount(block.timestamp)/52 ; token_contract.extMint(address(this), mintAmount); readyAt = block.timestamp.add(WEEK); currentRound = curren...
0.8.3
/** * @dev Get pricePerShare of a certain round (multiplied with ppsMultiplier!) * @param round Round to get the pricePerShare */
function getPricePerShare(uint256 round) public view returns (uint256 pps) { if (round == currentRound) { uint256 _assetBalance = assetBalance(); uint256 _shareSupply = totalSupply(); if (_shareSupply == 0) { pps = 1; } else { ...
0.8.3
// ------------------------------------------------------------------------ // 5 vev Tokens per 0.1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 10; } else { tokens = msg.value * 5; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); ...
0.4.25
/** * @notice Using a minimal proxy contract pattern initialises the contract and sets delegation * @dev initialises the VestingDepositAccount (see https://eips.ethereum.org/EIPS/eip-1167) * @dev only controller */
function init(address _tokenAddress, address _controller, address _beneficiary) external { require(controller == address(0), "VestingDepositAccount::init: Contract already initialized"); token = FuelToken(_tokenAddress); controller = _controller; beneficiary = _beneficiary; ...
0.5.16
/** * @notice Create a new vesting schedule * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @notice Delegation is set for the beneficiary on the token during schedule creation * @param _beneficiary beneficiary of the vested tokens * @param _amount amou...
function createVestingSchedule(address _beneficiary, uint256 _amount) external returns (bool) { require(msg.sender == owner, "VestingContract::createVestingSchedule: Only Owner"); require(_beneficiary != address(0), "VestingContract::createVestingSchedule: Beneficiary cannot be empty"); requi...
0.5.16
/** * @notice Updates a schedule beneficiary * @notice Voids the old schedule and transfers remaining amount to new beneficiary via a new schedule * @dev Only owner * @param _currentBeneficiary beneficiary to be replaced * @param _newBeneficiary beneficiary to vest remaining tokens to */
function updateScheduleBeneficiary(address _currentBeneficiary, address _newBeneficiary) external { require(msg.sender == owner, "VestingContract::updateScheduleBeneficiary: Only owner"); // retrieve existing schedule Schedule memory schedule = vestingSchedule[_currentBeneficiary]; ...
0.5.16
/** * @notice Vesting schedule and associated data for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _amount * @return _totalDrawn * @return _lastDrawnAt * @return _drawDownRate * @return _remainingBalance * @return _depositAccountAddress ...
function vestingScheduleForBeneficiary(address _beneficiary) external view returns ( uint256 _amount, uint256 _totalDrawn, uint256 _lastDrawnAt, uint256 _drawDownRate, uint256 _remainingBalance, address _depositAccountAddress ) { Schedule mem...
0.5.16
/** * @dev External function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */
function mint(address to, uint256 tokenId, uint256 metadataHash) external payable { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); require(msg.value >= _mintFee, "Fee not provided"); _feeRecipient.transfer(...
0.5.17
/** Claims tokens for free paying only gas fees */
function preMint( uint256 number, bytes32 messageHash, bytes calldata signature ) external virtual { require( hashMessage(number, msg.sender) == messageHash, "MESSAGE_INVALID" ); require( verifyAddressSigner(giftAddress, messageHash...
0.8.7
/** * @dev Set a token with a specific crew collection * @param _crewId The ERC721 tokenID for the crew member * @param _collId The set ID to assign the crew member to * @param _mod An optional modifier ranging from 0 (default) to 10,000 */
function setToken(uint _crewId, uint _collId, uint _mod) external onlyManagers { require(address(_generators[_collId]) != address(0), "CrewFeatures: collection must be defined"); _crewCollection[_crewId] = _collId; if (_mod > 0) { _crewModifiers[_crewId] = _mod; } }
0.7.6
// ============ Only-Solo Functions ============
function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory /* makerAccount */, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory /* d...
0.5.7
// concatenate the baseURI with the tokenId
function tokenURI(uint256 tokenId) public view virtual override returns(string memory) { require(_exists(tokenId), "token does not exist"); if (tokenIdToFrozenForArt[tokenId]) { string memory lockedBaseURI = _lockedBaseURI(); return bytes(lockedBaseURI).length > 0 ? string(...
0.8.7
// Used to request a 3D body for your voxmon // Freezes transfers re-rolling a voxmon
function request3DArt(uint256 tokenId) external { require(block.timestamp >= artStartTime, "you cannot freeze your Voxmon yet"); require(ownerOf(tokenId) == msg.sender, "you must own this token to request Art"); require(tokenIdToFrozenForArt[tokenId] == false, "art has already been requested ...
0.8.7
// Mint a Voxmon // Cost is 0.07 ether
function mint(address recipient) payable public returns (uint256) { require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one"); require(msg.value >= MINT_COST, "not enough ether, minting costs 0.07 ether"); require(block.timestamp >= startin...
0.8.7
// Mint multiple Voxmon // Cost is 0.07 ether per Voxmon
function mint(address recipient, uint256 numberToMint) payable public returns (uint256[] memory) { require(numberToMint > 0); require(numberToMint <= 10, "max 10 voxmons per transaction"); require(msg.value >= MINT_COST * numberToMint); uint256[] memory tokenIdsMinted = new uint256...
0.8.7
// Mint a free Voxmon
function preReleaseMint(address recipient) public returns (uint256) { require(remainingPreReleaseMints[msg.sender] > 0, "you have 0 remaining pre-release mints"); remainingPreReleaseMints[msg.sender] = remainingPreReleaseMints[msg.sender] - 1; require(_isTokenAvailable(), "max live supply r...
0.8.7
// Mint multiple free Voxmon
function preReleaseMint(address recipient, uint256 numberToMint) public returns (uint256[] memory) { require(remainingPreReleaseMints[msg.sender] >= numberToMint, "You don\'t have enough remaining pre-release mints"); uint256[] memory tokenIdsMinted = new uint256[](numberToMint); for(uint...
0.8.7
// Re-Roll a Voxmon // Cost is 0.01 ether
function reroll(uint256 tokenId) payable public returns (uint256) { require(ownerOf(tokenId) == msg.sender, "you must own this token to reroll"); require(msg.value >= REROLL_COST, "not enough ether, rerolling costs 0.03 ether"); require(tokenIdToFrozenForArt[tokenId] == false, "this token is ...
0.8.7
/** * @dev For each boosted vault, poke all the over boosted accounts. * @param _vaultAccounts An array of PokeVaultAccounts structs */
function poke(PokeVaultAccounts[] memory _vaultAccounts) external { uint vaultCount = _vaultAccounts.length; for(uint i = 0; i < vaultCount; i++) { PokeVaultAccounts memory vaultAccounts = _vaultAccounts[i]; address boostVaultAddress = vaultAccounts.boostVault; r...
0.8.2
// public sale
function safeMint(uint8 count) external payable { require(saleState == 3, "public sale is not begun"); require(count > 0 && count <= 3, "invalid count"); uint256 price = tokenPrice * count; require(msg.value >= price, "insufficient value"); payable(owner()).transfer(price); ...
0.8.12
// burn tokens, allowing sent ETH to be converted according to gweiPerGoof
function burnTokens(uint256 amount) private { if (msg.value > 0 && gweiPerGoof > 0) { uint256 converted = (msg.value * 1 gwei) / gweiPerGoof; if (converted >= amount) { amount = 0; } else { amount -= converted; } } i...
0.8.9
// This is the function that will be called postLoan // i.e. Encode the logic to handle your flashloaned funds here
function callFunction( address sender, Account.Info memory account, bytes memory data ) public { MyCustomData memory mcd = abi.decode(data, (MyCustomData)); IERC20 token1 = IERC20(mcd.loanedToken); IERC20 token2 = IERC20(mcd.otherToken); // STEP 1 ...
0.5.0
/** * @dev transfer token for a specified address and forward the parameters to token recipient if any * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _param1 Parameter 1 for the token recipient * @param _param2 Parameter 2 for the token recipient * @param _pa...
function transferWithParams(address _to, uint256 _value, uint256 _param1, uint256 _param2, uint256 _param3) onlyPayloadSize(5 * 32) external returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. ...
0.4.21
/** * @dev Buyouts a position's collateral * @param asset The address of the main collateral token of a position * @param user The owner of a position **/
function buyout(address asset, address user) public nonReentrant { require(vault.liquidationBlock(asset, user) != 0, "Unit Protocol: LIQUIDATION_NOT_TRIGGERED"); uint startingPrice = vault.liquidationPrice(asset, user); uint blocksPast = block.number.sub(vault.liquidationBlock(asset, user)); ...
0.7.5
/** * @notice The aim is to create a conditional payment and find someone to buy the counter position * * Parameters to forward to master contract: * @param long .. Decide if you want to be in the long or short position of your contract. * @param dueDate .. Set a due date of your contract. Make sure this is s...
function createContractWithBounty ( bool long, uint256 dueDate, uint256 strikePrice ) payable public { // New conditional payment must be created before deadline exceeded require(now < deadline); // Only once per creator address ...
0.5.8