lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
/// @notice function of proceed payment
/// @dev for only buy new factory
/// @return id of new factory
function _paymentProceed(uint256 _userId, Factory _factory) private returns(uint256) {
        User storage user = users[_userId];

        require(_checkPayment(user, _factory.ftype, _factory.level));

        uint256 price = getPrice(_factory.ftype, 0);
        user.balance = user.balance.add(msg.value);
        user.balance = user.balance.sub(price);
        user.totalPay = user.totalPay.add(price);
        totalDeposit += msg.value;

        uint256 index = factories.push(_factory) - 1;
        factoryToUser[index] = _userId;
        userToFactories[_userId].push(index);

        // distribute
        _distributeInvestment(msg.value);
        _distributeReferrers(_userId, price);
        _updateLeaders(msg.sender, msg.value);

        emit PaymentProceed(_userId, index, _factory.ftype, price);
        return index;
    }
// Solidity 0.4.24
/// @notice level up for factory
/// @param _factoryId id of factory
function levelUp(uint256 _factoryId) public payable onlyExistingUser {
        Factory storage factory = factories[_factoryId];
        uint256 price = getPrice(factory.ftype, factory.level + 1);

        uint256 userId = addressToUser[msg.sender];
        User storage user = users[userId];

        require(_checkPayment(user, factory.ftype, factory.level + 1));

        // payment
        user.balance = user.balance.add(msg.value);
        user.balance = user.balance.sub(price);
        user.totalPay = user.totalPay.add(price);
        totalDeposit += msg.value;

        _distributeInvestment(msg.value);
        _distributeReferrers(userId, price);

        // collect
        _collectResource(factory, user);
        factory.level++;

        _updateLeaders(msg.sender, msg.value);

        emit LevelUp(_factoryId, factory.level, userId, price);
    }
// Solidity 0.4.24
/// @notice function for collect all resources from all factories
/// @dev wrapper over _collectResource
function collectResources() public onlyExistingUser {
        uint256 index = addressToUser[msg.sender];
        User storage user = users[index];
        uint256[] storage factoriesIds = userToFactories[addressToUser[msg.sender]];

        for (uint256 i = 0; i < factoriesIds.length; i++) {
            _collectResource(factories[factoriesIds[i]], user);
        }
    }
// Solidity 0.6.12
// always results in incubation of 1 egg.
function startIncubate() public whenNotPausedIncubate nonReentrant{
        require (tme.balanceOf(msg.sender) >= tmePerIncubate, "Not enough TME");
        require (maxActiveIncubationsPerUser == 0 || ownerToNumActiveIncubations[msg.sender] < maxActiveIncubationsPerUser, "Max active incubations exceed");
        require (tme.transferFrom(address(msg.sender), address(this), tmePerIncubate), "Failed to transfer TME");
        uint256 newId = incubations.length;
        uint256 targetBlock = block.number + inbucateDurationInSecs.div(secsPerBlock) - 20; //buffer to make sure target block is earlier than end timestamp
        uint256 endTime = block.timestamp + inbucateDurationInSecs;
        Incubation memory incubation = Incubation(
            newId,
            block.number,
            targetBlock,
            msg.sender,
            block.timestamp,
            endTime,
            false,
            false,
            0
        );
        traitOracle.registerSeedForIncubation(targetBlock, msg.sender, block.timestamp, newId);

        incubations.push(incubation);
        ownerToNumIncubations[msg.sender] += 1;
        ownerToIds[msg.sender].push(newId);
        ownerToNumActiveIncubations[msg.sender] += 1;

        // require(incubations[newId].id == newId, "Sanity check for using id as arr index");

        emit IncubationStarted(msg.sender, block.timestamp, endTime);
    }
// Solidity 0.6.12
// called by backend to find out hatch result
function getResultOfIncubation(uint256 id) public view returns (bool, uint256){
        require (id < incubations.length, "invalid id");

        Incubation memory toHatch = incubations[id];
        require (toHatch.targetBlock < block.number, "not reached block");
        uint256 randomN = traitOracle.getRandomN(toHatch.targetBlock, toHatch.id);
        bool success = (_sliceNumber(randomN, SUCCESS_BIT_WIDTH, SUCCESS_OFFSET) >= HATCH_THRESHOLD);
        uint256 randomN2 = uint256(keccak256(abi.encodePacked(randomN)));
        uint256 traits = getTraitsFromRandom(randomN2);

        return (success, traits);
    }
// Solidity 0.6.12
/// @dev given a number get a slice of any bits, at certain offset
/// @param _n a number to be sliced
/// @param _nbits how many bits long is the new number
/// @param _offset how many bits to skip
function _sliceNumber(uint256 _n, uint8 _nbits, uint8 _offset) private pure returns (uint8) {
        // mask is made by shifting left an offset number of times
        uint256 mask = uint256((2**uint256(_nbits)) - 1) << _offset;
        // AND n with mask, and trim to max of _nbits bits
        return uint8((_n & mask) >> _offset);
    }
// Solidity 0.4.24
/// INITIALIZATION FUNCTIONALITY ///
function initialize() public {
        require(!initialized, "Contract is already initialized");
        owner = msg.sender;
        proposedOwner = address(0);
        assetProtectionRole = address(0);
        totalSupply_ = 0;
        supplyController = msg.sender;
        feeRate = 0;
        feeController = msg.sender;
        feeRecipient = msg.sender;
        initialized = true;
    }
// Solidity 0.4.24
/// ERC20 FUNCTIONALITY ///
function transferFrom(
        address _from,
        address _to,
        uint256 _value
    )
    public
    whenNotPaused
    returns (bool)
    {
        require(_to != address(0), "cannot transfer to address zero");
        require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen");
        require(_value <= balances[_from], "insufficient funds");
        require(_value <= allowed[_from][msg.sender], "insufficient allowance");

        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
        _transfer(_from, _to, _value);

        return true;
    }
// Solidity 0.4.25
// Increase the lock balance of a specific person.
// If you only want to increase the balance, the release_time must be specified in advance.
function increaseLockBalance(address _holder, uint256 _value)
    public
    onlyOwner
    returns (bool)
  {
	require(_holder != address(0));
	require(_value > 0);
	require(balanceOf(_holder) >= _value);
	
	if (userLock[_holder].release_time == 0) {
		userLock[_holder].release_time = block.timestamp + lock_period;
	}
	
	userLock[_holder].locked_balance = (userLock[_holder].locked_balance).add(_value);
	emit Locked(_holder, _value, userLock[_holder].locked_balance, userLock[_holder].release_time);
	return true;
  }
// Solidity 0.7.4
/// @notice update pool's rewards & bonus per staked token till current block timestamp
function updatePool(address _lpToken) public override {
    Pool storage pool = pools[_lpToken];
    if (block.timestamp <= pool.lastUpdatedAt) return;
    uint256 lpTotal = IERC20(_lpToken).balanceOf(address(this));
    if (lpTotal == 0) {
      pool.lastUpdatedAt = block.timestamp;
      return;
    }
    // update COVER rewards for pool
    uint256 coverRewards = _calculateCoverRewardsForPeriod(pool);
    pool.accRewardsPerToken = pool.accRewardsPerToken.add(coverRewards.div(lpTotal));
    pool.lastUpdatedAt = block.timestamp;
    // update bonus token rewards if exist for pool
    BonusToken storage bonusToken = bonusTokens[_lpToken];
    if (bonusToken.lastUpdatedAt < bonusToken.endTime && bonusToken.startTime < block.timestamp) {
      uint256 bonus = _calculateBonusForPeriod(bonusToken);
      bonusToken.accBonusPerToken = bonusToken.accBonusPerToken.add(bonus.div(lpTotal));
      bonusToken.lastUpdatedAt = block.timestamp <= bonusToken.endTime ? block.timestamp : bonusToken.endTime;
    }
  }
// Solidity 0.7.4
/// @notice withdraw all without rewards
function emergencyWithdraw(address _lpToken) external override {
    Miner storage miner = miners[_lpToken][msg.sender];
    uint256 amount = miner.amount;
    require(miner.amount > 0, "Blacksmith: insufficient balance");
    miner.amount = 0;
    miner.rewardWriteoff = 0;
    _safeTransfer(_lpToken, amount);
    emit Withdraw(msg.sender, _lpToken, amount);
  }
// Solidity 0.7.4
/// @notice update pool weights
function updatePoolWeights(address[] calldata _lpTokens, uint256[] calldata _weights) public override onlyGovernance {
    for (uint256 i = 0; i < _lpTokens.length; i++) {
      Pool storage pool = pools[_lpTokens[i]];
      if (pool.lastUpdatedAt > 0) {
        totalWeight = totalWeight.add(_weights[i]).sub(pool.weight);
        pool.weight = _weights[i];
      }
    }
  }
// Solidity 0.7.4
/// @notice add a new pool for shield mining
function addPool(address _lpToken, uint256 _weight) public override onlyOwner {
    Pool memory pool = pools[_lpToken];
    require(pool.lastUpdatedAt == 0, "Blacksmith: pool exists");
    pools[_lpToken] = Pool({
      weight: _weight,
      accRewardsPerToken: 0,
      lastUpdatedAt: block.timestamp
    });
    totalWeight = totalWeight.add(_weight);
    poolList.push(_lpToken);
  }
// Solidity 0.7.4
/// @notice add new pools for shield mining
function addPools(address[] calldata _lpTokens, uint256[] calldata _weights) external override onlyOwner {
    require(_lpTokens.length == _weights.length, "Blacksmith: size don't match");
    for (uint256 i = 0; i < _lpTokens.length; i++) {
     addPool(_lpTokens[i], _weights[i]);
    }
  }
// Solidity 0.7.4
/// @notice always assign the same startTime and endTime for both CLAIM and NOCLAIM pool, one bonusToken can be used for only one set of CLAIM and NOCLAIM pools
function addBonusToken(
    address _lpToken,
    address _bonusToken,
    uint256 _startTime,
    uint256 _endTime,
    uint256 _totalBonus
  ) external override {
    IERC20 bonusToken = IERC20(_bonusToken);
    require(pools[_lpToken].lastUpdatedAt != 0, "Blacksmith: pool does NOT exist");
    require(allowBonusTokens[_bonusToken] == 1, "Blacksmith: bonusToken not allowed");

    BonusToken memory currentBonusToken = bonusTokens[_lpToken];
    if (currentBonusToken.totalBonus != 0) {
      require(currentBonusToken.endTime.add(WEEK) < block.timestamp, "Blacksmith: last bonus period hasn't ended");
      require(IERC20(currentBonusToken.addr).balanceOf(address(this)) == 0, "Blacksmith: last bonus not all claimed");
    }

    require(_startTime >= block.timestamp && _endTime > _startTime, "Blacksmith: messed up timeline");
    require(_totalBonus > 0 && bonusToken.balanceOf(msg.sender) >= _totalBonus, "Blacksmith: incorrect total rewards");

    uint256 balanceBefore = bonusToken.balanceOf(address(this));
    bonusToken.safeTransferFrom(msg.sender, address(this), _totalBonus);
    uint256 balanceAfter = bonusToken.balanceOf(address(this));
    require(balanceAfter > balanceBefore, "Blacksmith: incorrect total rewards");

    bonusTokens[_lpToken] = BonusToken({
      addr: _bonusToken,
      startTime: _startTime,
      endTime: _endTime,
      totalBonus: balanceAfter.sub(balanceBefore),
      accBonusPerToken: 0,
      lastUpdatedAt: _startTime
    });
  }
// Solidity 0.7.4
/// @notice collect dust to treasury
function collectDust(address _token) external override {
    Pool memory pool = pools[_token];
    require(pool.lastUpdatedAt == 0, "Blacksmith: lpToken, not allowed");
    require(allowBonusTokens[_token] == 0, "Blacksmith: bonusToken, not allowed");

    IERC20 token = IERC20(_token);
    uint256 amount = token.balanceOf(address(this));
    require(amount > 0, "Blacksmith: 0 to collect");

    if (_token == address(0)) { // token address(0) == ETH
      payable(treasury).transfer(amount);
    } else {
      token.safeTransfer(treasury, amount);
    }
  }
// Solidity 0.7.4
/// @notice collect bonus token dust to treasury
function collectBonusDust(address _lpToken) external override {
    BonusToken memory bonusToken = bonusTokens[_lpToken];
    require(bonusToken.endTime.add(WEEK) < block.timestamp, "Blacksmith: bonusToken, not ready");

    IERC20 token = IERC20(bonusToken.addr);
    uint256 amount = token.balanceOf(address(this));
    require(amount > 0, "Blacksmith: 0 to collect");
    token.safeTransfer(treasury, amount);
  }
// Solidity 0.7.4
/// @notice tranfer upto what the contract has
function _safeTransfer(address _token, uint256 _amount) private nonReentrant {
    IERC20 token = IERC20(_token);
    uint256 balance = token.balanceOf(address(this));
    if (balance > _amount) {
      token.safeTransfer(msg.sender, _amount);
    } else if (balance > 0) {
      token.safeTransfer(msg.sender, balance);
    }
  }
// Solidity 0.8.7
// mint all tokens to the owner
// function _reserve() private {
//     address payable sender = msgSender();
//     for (uint256 i = 0; i < maxNftSupply; i++) {
//         _safeMint(sender, i, "");
//     }
// }
function buy(uint256 tokenId) public payable {
        require(activeContract, "Contract is not active");
        uint kind = tokenId / MAX_TOKENS_PER_KIND;
        require(kind < contracts.length, "TokenId error");
        uint extTokenId = tokenId % MAX_TOKENS_PER_KIND;
        require(contracts[kind].ownerOf(extTokenId) == msgSender(), "You do not own the item");
        if (!ifWhitelist(msgSender())){
            require(msg.value >= price - 100, "not enough payment");
        }
        else{
            deladd(msgSender());
        }
        _safeMint(msgSender(), tokenId);
    }
// Solidity 0.7.0
/**
 *  @dev Mint tokens for community
 */
function mintCommunityTokens(uint256 numberOfTokens) public onlyOwner {
        require(numberOfTokens <= MAX_TOTAL_TOKENS);
        require(
            numberOfTokens <= MAX_TOTAL_TOKENS,
            "Can not mint more than the total supply."
        );
        require(
            totalSupply().add(numberOfTokens) <= MAX_TOTAL_TOKENS,
            "Minting would exceed max supply of Tokens"
        );
        uint256 supply = totalSupply();
        for (uint256 i = 0; i < numberOfTokens; i++) {
            if (totalSupply() < MAX_TOTAL_TOKENS) {
                _safeMint(msg.sender, supply + i);
            }
        }
    }
// Solidity 0.7.0
/**
 *  @dev Mint token to an address
 */
function mintTokenTransfer(address to, uint256 numberOfTokens)
        public
        onlyOwner
    {
        require(numberOfTokens <= MAX_TOTAL_TOKENS);
        require(
            numberOfTokens <= MAX_TOTAL_TOKENS,
            "Can not mint more than the total supply."
        );
        require(
            totalSupply().add(numberOfTokens) <= MAX_TOTAL_TOKENS,
            "Minting would exceed max supply of Tokens"
        );
        require(
            address(to) != address(this),
            "Cannot mint to contract itself."
        );
        require(address(to) != address(0), "Cannot mint to the null address.");
        uint256 supply = totalSupply();
        for (uint256 i = 0; i < numberOfTokens; i++) {
            if (totalSupply() < MAX_TOTAL_TOKENS) {
                _safeMint(to, supply + i);
            }
        }
    }
// Solidity 0.8.7
/**
 * toss a coin to yung wknd
 * oh valley of plenty
 */
function withdraw(address _to) public {
        require(IERC721(_creator).ownerOf(_tokenId) == msg.sender, "Only collector can withdraw");
        require(numMints == 100, "Can only withdraw when sold out");
        // Have you ever waltzed into someone's home and taken something without their permission?
        uint balance = address(this).balance;
        uint tax = balance * 69 / 1000;
        uint kept = balance - tax;

        // The taxman cometh
        payable(_collector).transfer(tax);
        payable(_to).transfer(kept);
    }
// Solidity 0.4.24
//When transfer tokens decrease dividendPayments for sender and increase for receiver
function transfer(address _to, uint256 _value) public returns (bool) {
        // balance before transfer
        uint256 oldBalanceFrom = balances[msg.sender];

        // invoke super function with requires
        bool isTransferred = super.transfer(_to, _value);

        uint256 transferredClaims = dividendPayments[msg.sender].mul(_value).div(oldBalanceFrom);
        dividendPayments[msg.sender] = dividendPayments[msg.sender].sub(transferredClaims);
        dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);

        return isTransferred;
    }
// Solidity 0.4.24
//When transfer tokens decrease dividendPayments for token owner and increase for receiver
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        // balance before transfer
        uint256 oldBalanceFrom = balances[_from];

        // invoke super function with requires
        bool isTransferred = super.transferFrom(_from, _to, _value);

        uint256 transferredClaims = dividendPayments[_from].mul(_value).div(oldBalanceFrom);
        dividendPayments[_from] = dividendPayments[_from].sub(transferredClaims);
        dividendPayments[_to] = dividendPayments[_to].add(transferredClaims);

        return isTransferred;
    }
// Solidity 0.4.24
// Get bonus percent
function _getBonusPercent() internal view returns(uint256) {

        if (now < endPeriodA) {
            return 40;
        }
        if (now < endPeriodB) {
            return 25;
        }
        if (now < endPeriodC) {
            return 20;
        }

        return 15;
    }
// Solidity 0.4.24
// Success finish of PreSale
function finishPreSale() public onlyOwner {
        require(totalRaised >= softCap);
        require(now > endTime);

        // withdrawal all eth from contract
        _forwardFunds(address(this).balance);

        // withdrawal all T4T tokens from contract
        _forwardT4T(t4tToken.balanceOf(address(this)));

        // transfer ownership of tokens to owner
        icsToken.transferOwnership(owner);
        hicsToken.transferOwnership(owner);
    }
// Solidity 0.4.24
// buy tokens - helper function
// @param _beneficiary address of beneficiary
// @param _value of tokens (1 token = 10^18)
function _buyTokens(address _beneficiary, uint256 _value) internal {
        // calculate HICS token amount
        uint256 valueHics = _value.div(5);  // 20% HICS and 80% ICS Tokens

        if (_value >= hicsTokenPrice
        && hicsToken.totalSupply().add(_getTokenNumberWithBonus(valueHics)) < capHicsToken) {
            // 20% HICS and 80% ICS Tokens
            _buyIcsTokens(_beneficiary, _value - valueHics);
            _buyHicsTokens(_beneficiary, valueHics);
        } else {
            // 100% of ICS Tokens
            _buyIcsTokens(_beneficiary, _value);
        }

        // update states
        uint256 tokensWithBonus = _getTokenNumberWithBonus(_value);
        totalTokensEmitted = totalTokensEmitted.add(tokensWithBonus);
        balances[_beneficiary] = balances[_beneficiary].add(tokensWithBonus);

        totalRaised = totalRaised.add(_value);
    }
// Solidity 0.4.24
// buy tokens for T4T tokens
// @param _beneficiary address of beneficiary
function buyTokensT4T(address _beneficiary) public saleIsOn {
        require(_beneficiary != address(0));

        uint256 valueT4T = t4tToken.allowance(_beneficiary, address(this));

        // check minimumInvest
        uint256 value = valueT4T.mul(rateT4T);
        require(value >= minimumInvest);

        // transfer T4T from _beneficiary to this contract
        require(t4tToken.transferFrom(_beneficiary, address(this), valueT4T));

        _buyTokens(_beneficiary, value);

        // only for buy using T4T tokens
        t4tRaised = t4tRaised.add(valueT4T);
        balancesForRefundT4T[_beneficiary] = balancesForRefundT4T[_beneficiary].add(valueT4T);
    }
// Solidity 0.4.24
// low level token purchase function
// @param _beneficiary address of beneficiary
function buyTokens(address _beneficiary) saleIsOn public payable {
        require(_beneficiary != address(0));

        uint256 weiAmount = msg.value;
        uint256 value = weiAmount.mul(rate);
        require(value >= minimumInvest);

        _buyTokens(_beneficiary, value);

        // only for buy using PreSale contract
        weiRaised = weiRaised.add(weiAmount);
        balancesForRefund[_beneficiary] = balancesForRefund[_beneficiary].add(weiAmount);
    }
// Solidity 0.8.12
// URI will be returned as baseUri/tokenId
function safeMint(address to, string memory baseUri) public onlyOwner {
        require(!_supplyIsLocked, "SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.");
        uint16 tokenId = _tokenIdCounter + 1;
        _safeMint(to, tokenId);
        _baseUri = baseUri;
        _tokenIdCounter = tokenId;
    }
// Solidity 0.8.12
// URIs will be returned baseUri/tokenId
function safeMintBatch(address to, string memory baseUri, uint16 numTokens) public onlyOwner {
        require(!_supplyIsLocked, "SussyKneelsNFT: Supply has been permanently locked, no minting is allowed.");
        uint16 counter = _tokenIdCounter;
        for(uint16 i=0; i<numTokens; i++) {
            counter++;
            _safeMint(to, counter);
        }
        _baseUri = baseUri;
        _tokenIdCounter = counter;
    }
// Solidity 0.4.18
// ERC20 token transfer function with additional safety
function transfer(address _to, uint256 _amount) public returns (bool success) {
    require(!(_to == 0x0));
    if ((balances[msg.sender] >= _amount)
    && (_amount > 0)
    && ((safeAdd(balances[_to],_amount) > balances[_to]))) {
      balances[msg.sender] = safeSub(balances[msg.sender], _amount);
      balances[_to] = safeAdd(balances[_to], _amount);
      Transfer(msg.sender, _to, _amount);
      return true;
    } else {
      return false;
    }
  }
// Solidity 0.4.18
// ERC20 token transferFrom function with additional safety
function transferFrom(
    address _from,
    address _to,
    uint256 _amount) public returns (bool success) {
    require(!(_to == 0x0));
    if ((balances[_from] >= _amount)
    && (allowed[_from][msg.sender] >= _amount)
    && (_amount > 0)
    && (safeAdd(balances[_to],_amount) > balances[_to])) {
      balances[_from] = safeSub(balances[_from], _amount);
      allowed[_from][msg.sender] = safeSub((allowed[_from][msg.sender]),_amount);
      balances[_to] = safeAdd(balances[_to], _amount);
      Transfer(_from, _to, _amount);
      return true;
    } else {
      return false;
    }
  }
// Solidity 0.4.18
// ERC20 allow _spender to withdraw, multiple times, up to the _value amount
function approve(address _spender, uint256 _amount) public returns (bool success) {
    //Fix for known double-spend https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit#
    //Input must either set allow amount to 0, or have 0 already set, to workaround issue
    require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
    require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
    allowed[msg.sender][_spender] = _amount;
    Approval(msg.sender, _spender, _amount);
    return true;
  }
// Solidity 0.4.18
// ERC20 Updated decrease approval process (to prevent double-spend attack but remove need to zero allowance before setting)
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
    uint oldValue = allowed[msg.sender][_spender];

    if (_subtractedValue > oldValue) {
      allowed[msg.sender][_spender] = 0;
    } else {
      allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue);
    }

    // report new approval amount
    Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
    return true;
  }