lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.23
// ------------------------------------------------------------------------
// Transfer _amount tokens to address _to 
// Sender must have enough tokens. Cannot send to 0x0.
// ------------------------------------------------------------------------
function transfer(address _to, uint _amount) 
    public 
    returns (bool success) {
        require(_to != address(0));         // Use burn() function instead
        require(_to != address(this));
        balances[msg.sender] = balances[msg.sender].sub(_amount);
        balances[_to] = balances[_to].add(_amount);
        emit Transfer(msg.sender, _to, _amount);
        return true;
    }
// Solidity 0.4.23
// Allows the Hydro API to set minimum hydro balances required for sign ups
function setMinimumHydroStakes(uint newMinimumHydroStakeUser, uint newMinimumHydroStakeDelegatedUser)
        public onlyOwner
    {
        ERC20Basic hydro = ERC20Basic(hydroTokenAddress);
        require(newMinimumHydroStakeUser <= (hydro.totalSupply() / 100 / 100)); // <= .01% of total supply
        require(newMinimumHydroStakeDelegatedUser <= (hydro.totalSupply() / 100 / 2)); // <= .5% of total supply
        minimumHydroStakeUser = newMinimumHydroStakeUser;
        minimumHydroStakeDelegatedUser = newMinimumHydroStakeDelegatedUser;
    }
// Solidity 0.4.23
// Checks prefixed signatures (e.g. those created with web3.eth.sign)
function _isSignedPrefixed(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s)
        internal
        pure
        returns (bool)
    {
        bytes memory prefix = "\x19Ethereum Signed Message:\n32";
        bytes32 prefixedMessageHash = keccak256(prefix, messageHash);

        return ecrecover(prefixedMessageHash, v, r, s) == _address;
    }
// Solidity 0.4.23
// Common internal logic for all user signups
function _userSignUp(string casedUserName, address userAddress, bool delegated) internal {
        require(bytes(casedUserName).length < 50);

        bytes32 uncasedUserNameHash = keccak256(casedUserName.toSlice().copy().toString().lower());
        require(!userDirectory[uncasedUserNameHash]._initialized);

        userDirectory[uncasedUserNameHash] = User(casedUserName, userAddress, delegated, true);
        nameDirectory[userAddress] = uncasedUserNameHash;

        emit UserSignUp(casedUserName, userAddress, delegated);
    }
// Solidity 0.8.7
// Overridden ownerOf
function approve(address to, uint256 tokenId) public virtual override {
        address owner = ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            msg.sender == owner || isApprovedForAll(owner, msg.sender),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }
// Solidity 0.8.7
// Removed ERC721 specifier to use overridden ownerOf function
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }
// Solidity 0.8.7
// OpenZeppelin _mint function overriden to support quantity. This reduces
// writes to storage and simplifies code.
//
// Flag added to allow selection between "safe" and "unsafe" mint with one
// function.
function _mint(address to, uint256 quantity, uint256 safeMint, bytes memory data) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");

        // Reading tokenIndex into memory, and then updating
        // balances and stored index one time is more gas
        // efficient.
        uint256 mintIndex = _tokenIndex;
        _minted[to] += quantity;
        _tokenIndex += quantity;

        // Mint new tokens.
        for (uint256 i = 0; i < quantity; i++) {
            mintIndex++;
            _owners[mintIndex] = to;
            emit Transfer(address(0), to, mintIndex);
            emit PermanentURI("https://frenlyflyz.io/ffmp-token-metadata/", mintIndex);

            if (safeMint == 1) {
                require(
                    _checkOnERC721Received(address(0), to, mintIndex, data),
                    "ERC721: transfer to non ERC721Receiver implementer"
                );
            }
        }
    }
// Solidity 0.8.7
//Function overridden in main contract.
function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);
    }
// Solidity 0.4.23
// ------------------------------------------------------------------------
// An approved sender can burn _amount tokens of user _from
// Lowers user balance and supply by _amount 
// ------------------------------------------------------------------------    
function burnFrom(address _from, uint _amount) 
    public 
    returns (bool success) {
        balances[_from] = balances[_from].sub(_amount);                         // Subtract from the targeted balance
        allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);             // Subtract from the sender's allowance
        supply = supply.sub(_amount);                              // Update supply
        emit LogBurn(_from, _amount);
        emit Transfer(_from, address(0), _amount);
        return true;
    }
// Solidity 0.4.23
// ------------------------------------------------------------------------
// Users can trade old MyBit tokens for new MyBit tokens here 
// Must approve this contract as spender to swap tokens
// ------------------------------------------------------------------------
function swap(uint256 _amount) 
  public 
  noMint
  returns (bool){ 
    require(ERC20Interface(oldTokenAddress).transferFrom(msg.sender, this, _amount));
    uint256 newTokenAmount = _amount.mul(scalingFactor).mul(tenDecimalPlaces);   // Add 10 more decimals to number of tokens
    assert(tokensRedeemed.add(newTokenAmount) <= circulatingSupply);       // redeemed tokens should never exceed circulatingSupply
    tokensRedeemed = tokensRedeemed.add(newTokenAmount);
    require(newToken.transfer(msg.sender, newTokenAmount));
    emit LogTokenSwap(msg.sender, _amount, block.timestamp);
    return true;
  }
// Solidity 0.4.23
// ------------------------------------------------------------------------
// Alias for swap(). Called by old token contract when approval to transfer 
// tokens has been given. 
// ------------------------------------------------------------------------
function receiveApproval(address _from, uint256 _amount, address _token, bytes _data)
  public 
  noMint
  returns (bool){ 
    require(_token == oldTokenAddress);
    require(ERC20Interface(oldTokenAddress).transferFrom(_from, this, _amount));
    uint256 newTokenAmount = _amount.mul(scalingFactor).mul(tenDecimalPlaces);   // Add 10 more decimals to number of tokens
    assert(tokensRedeemed.add(newTokenAmount) <= circulatingSupply);    // redeemed tokens should never exceed circulatingSupply
    tokensRedeemed = tokensRedeemed.add(newTokenAmount);
    require(newToken.transfer(_from, newTokenAmount));
    emit LogTokenSwap(_from, _amount, block.timestamp);
    return true;
  }
// Solidity 0.8.7
// manual burn amount, for *possible* cex integration
// !!BEWARE!!: you will BURN YOUR TOKENS when you call this.
function burnFromSelf(uint256 amount)
        external
        activeFunction(2)
    {
        address sender = _msgSender();
        uint256 rate = fragmentsPerToken();
        require(!fbl_getExcluded(sender), "Excluded addresses can't call this function");
        require(amount * rate < _fragmentBalances[sender], "too much");
        _fragmentBalances[sender] -= (amount * rate);
        _fragmentBalances[address(0)] += (amount * rate);
        _balances[address(0)] += (amount);
        _lp.sync();
        _lp.skim(treasury);
        emit Transfer(address(this), address(0), amount);
    }
// Solidity 0.8.7
/* !!! CALLER WILL LOSE COINS CALLING THIS !!! */
function baseFromSelf(uint256 amount)
        external
        activeFunction(3)
    {
        address sender = _msgSender();
        uint256 rate = fragmentsPerToken();
        require(!fbl_getExcluded(sender), "Excluded addresses can't call this function");
        require(amount * rate < _fragmentBalances[sender], "too much");
        _fragmentBalances[sender] -= (amount * rate);
        _totalFragments -= amount * rate;
        feesAccruedByUser[sender] += amount;
        feesAccrued += amount;
    }
// Solidity 0.6.12
/**
 * @param amount Amount of staking tokens
 * @param lockDays How many days the staker wants to lock
 * @param rewardToken The desired reward token to stake the tokens for (most likely a certain uToken)
 */
function stake(uint256 amount, uint256 lockDays, address rewardToken)
        external
        poolExists(rewardToken)
    {
        require(
            amount >= minStakeAmount,
            "UnicStaking: Amount must be greater than or equal to min stake amount"
        );
        require(
            lockMultipliers[lockDays].exists,
            "UnicStaking: Invalid number of lock days specified"
        );

        updateRewards(rewardToken);

        // transfer the staking tokens into the staking pool
        stakingToken.safeTransferFrom(msg.sender, address(this), amount);

        // now the data of the staker is persisted
        StakerInfo storage staker = stakes[nftStartId];
        staker.stakeStartTime = block.timestamp;
        staker.amount = amount;
        staker.lockDays = lockDays;
        staker.multiplier = lockMultipliers[lockDays].multiplier;
        staker.nftId = nftStartId;
        staker.rewardToken = rewardToken;

        RewardPool storage pool = pools[rewardToken];

        // the amount with lock multiplier applied
        uint256 virtualAmount = virtualAmount(staker.amount, staker.multiplier);
        staker.rewardDebt = virtualAmount.mul(pool.accRewardPerShare).div(DIV_PRECISION);

        pool.stakedAmount = pool.stakedAmount.add(amount);
        pool.stakedAmountWithMultipliers = pool.stakedAmountWithMultipliers.add(virtualAmount);

        nftStartId = nftStartId.add(1);
        nftCollection.mint(msg.sender, nftStartId - 1);

        emit Staked(msg.sender, rewardToken, nftStartId, amount, lockDays);
    }
// Solidity 0.8.4
/// Accepts ether and creates new LifeCoin tokens.
function depositETH() external payable {
	  require(!isFinalized, "Already finalized");
	  require(block.timestamp >= fundingStartBlock, "Current block-number should not be less than fundingStartBlock");
	  require(block.timestamp <= fundingEndBlock, "Current block-number should not be greater than fundingEndBlock");
	  require(msg.value > 0, "Ether not sent");

      uint256 weekIndex = (block.timestamp - fundingStartBlock) / blocksPerWeek;  // Calculate the array index to credit account
      uint256 currentBalance = icoEthBalances[msg.sender][weekIndex];
      icoEthBalances[msg.sender][weekIndex] = safeAdd(currentBalance, msg.value); //Credit the senders account for the bonus period.

      // Store the totals for each week
      uint256 currentETHWeek = icoEthPerWeek[weekIndex];
      icoEthPerWeek[weekIndex] = safeAdd(currentETHWeek, msg.value); //Credit the senders account for the bonus period.
      emit DepositETH(msg.sender, msg.value, weekIndex);                                          // Log the deposit.
    }
// Solidity 0.8.4
/// Ends the funding period and sends the ETH to the ethFundDeposit.
function finalize() external {
      assert(address(this).balance > 0);
	  require(!isFinalized, "Already finalized");
      require(msg.sender == ethFundDeposit, "Sender should be ethFundDeposit"); // locks finalize to the ultimate ETH owner
	  require(block.timestamp > fundingEndBlock, "Current block-number is not greater than fundingEndBlock");
      //Calculate the base exchange rate

      uint256 totalEffectiveWei = 0;
      for(uint32 i =0; i < 7; i++){
        totalEffectiveWei = safeAdd(totalEffectiveWei, icoEthPerWeek[i]);
      }

      //Convert to wei
      baseLifeCoinExchangeRate = ((totalLifeCoins - yawLifeFund)*1e29) / totalEffectiveWei; //((totalLifeCoins - yawLifeFund)*1e29) / totalEffectiveWei
      // switch to operational
      isFinalized = true;
      balances[yawLifeFundDeposit] += yawLifeFund;       // Credit YawLife Pty. Ltd. After the ICO Finishes.
      emit CreateLifeCoin(yawLifeFundDeposit, yawLifeFund);  // Log the creation of the first new LifeCoin Tokens.
	  payable(ethFundDeposit).transfer(address(this).balance);   // send the eth to YawLife Pty. Ltd.
    }
// Solidity 0.8.4
/// After the ICO - Allow participants to withdraw their tokens at the price dictated by amount of ETH raised.
function withdraw() external {
      assert(isFinalized == true);            // Wait until YawLife has checked and confirmed the details of the ICO before withdrawing tokens.
      //VERIFY THIS
      // Check balance. Only permit if balance is non Zero
      uint256 balance =0;
      for(uint256 k=0; k < 7; k++){
        balance = safeAdd(balance, icoEthBalances[msg.sender][k]);
      }
      assert(balance > 0);  // TODO: CHECK THIS

      uint256 lifeCoinsOwed=0;
      uint256 effectiveWeiInvestment =0;
      for(uint32 i =0; i < 7; i++ ) {
          effectiveWeiInvestment = icoEthBalances[msg.sender][i];
          // Convert exchange rate to Wei after multiplying.
          lifeCoinsOwed = safeAdd(lifeCoinsOwed, baseLifeCoinExchangeRate*effectiveWeiInvestment/1e29); //baseLifeCoinExchangeRate*effectiveWeiInvestment/1e29
          icoEthBalances[msg.sender][i] = 0;
      }
      balances[msg.sender] = lifeCoinsOwed; // Credit the participants account with LifeCoins.
      emit CreateLifeCoin(msg.sender, lifeCoinsOwed); // Log the creation of new coins.
    }
// Solidity 0.4.21
// enforce minimum spend to buy tokens
function ICO( address _erc20,
                address _treasury,
                uint _startSec,
                uint _durationSec,
                uint _tokpereth ) public
  {
    require( isContract(_erc20) );
    require( _tokpereth > 0 );

    if (_treasury != address(0)) require( isContract(_treasury) );

    tokenSC = ERC20( _erc20 );
    treasury = _treasury;
    start = _startSec;
    duration = _durationSec;
    tokpereth = _tokpereth;
    minfinney = 25;
  }
// Solidity 0.4.17
///The distribution function, accumulated tokens on a variable dividend among members
function dividendDistribution () onlyOwner public {
         Transfer(0, this, dividend);
         uint256 divsum = dividend / members.length; 
         dividend = 0;
         for (uint i = 0; i < members.length; i++) {
        address AdToDiv = members[i].member ;
         balanceOf[AdToDiv] += divsum;
         Transfer(this, AdToDiv, divsum);
                }
       
}
// Solidity 0.7.6
/*
 @dev Uniswap fails with zero address so no check is necessary here
 */
function _swap(
        address _dex,
        address _tokenIn,
        address _tokenOut,
        uint _amount
    ) private {
        // create dynamic array with 3 elements
        address[] memory path = new address[](3);
        path[0] = _tokenIn;
        path[1] = WETH;
        path[2] = _tokenOut;

        UniswapV2Router(_dex).swapExactTokensForTokens(
            _amount,
            1,
            path,
            address(this),
            block.timestamp
        );
    }
// Solidity 0.7.6
/*
 @notice Transfer token accidentally sent here to admin
 @param _token Address of token to transfer
 */
function sweep(address _token) external override onlyAuthorized {
        require(_token != address(token), "protected token");
        for (uint i = 0; i < NUM_REWARDS; i++) {
            require(_token != REWARDS[i], "protected token");
        }
        IERC20(_token).safeTransfer(admin, IERC20(_token).balanceOf(address(this)));
    }
// Solidity 0.4.17
/// Pile robbery function of pantry owner contract. (tokens)
function robPantryT (address target, uint256 amount) onlyOwner public {
        require(amount <= balanceOf[this]);
        balanceOf[this] -= amount;                         // Subtract from the sender
        balanceOf[target] += amount;                           // Add the same to the recipient
        Transfer(this, target, amount);
     }
// Solidity 0.6.12
// WETH -> VaultX -> XWETH -> Bridge -> PXWETH
// _toAddress need to be little endian and start with 0x fef: https://peterlinx.github.io/DataTransformationTools/
function lock(bytes memory _toAddress, uint256 _amount) public {
        // need approve infinte amount from user then safe transfer from
        IERC20(want).safeTransferFrom(msg.sender, address(this), _amount);
        IERC20(want).safeApprove(xvault, _amount);
        Vault(xvault).deposit(_amount);
        // https://github.com/polynetwork/eth-contracts/blob/master/contracts/core/lock_proxy/LockProxy.sol#L64
        IERC20(xvault).safeApprove(polyLockProxy, _amount);
        // 4 -> neo mainnet 5 -> neo testnet
        LockProxy(polyLockProxy).lock(xvault, toChainId, _toAddress, _amount);
    }
// Solidity 0.6.12
//--------------------------------------------------------------------------------------------------------------------------
// Price calculator:
//--------------------------------------------------------------------------------------------------------------------------
function calcPrice(address _fromAsset, uint256 _fromAmount) public view returns (uint256 toActualAmount_, uint256 fromActualAmount_)
    {
        require(_fromAmount > 0, "ERR_ZERO_PAYMENT");
        
        uint256 fromAssetPrice = assets[_fromAsset];
        require(fromAssetPrice > 0, "ERR_ASSET_NOT_SUPPORTED");
        
        if(isSwapPaused) return (0, 0);
        
        uint256 toAvailableForSell = availableForSellAmount();
        
        fromActualAmount_ = _fromAmount;

        toActualAmount_ = _fromAmount.mul(ONE).div(fromAssetPrice);
        
        if(toActualAmount_ > toAvailableForSell)
        {
            toActualAmount_ = toAvailableForSell;
            fromActualAmount_ = toAvailableForSell.mul(fromAssetPrice).div(ONE);
        }
    }
// Solidity 0.4.24
/// @dev will open the trading for everyone
function closeSale() external onlyOwner beforeSaleClosed {
        /// The unsold and unallocated bounty tokens are allocated to the platform tokens

        uint256 unsoldTokens = balances[saleTokensAddress];
        balances[platformTokensAddress] = balances[platformTokensAddress].add(unsoldTokens);
        balances[saleTokensAddress] = 0;
        emit Transfer(saleTokensAddress, platformTokensAddress, unsoldTokens);

        uint256 unallocatedBountyTokens = balances[referralBountyTokensAddress];
        balances[platformTokensAddress] = balances[platformTokensAddress].add(unallocatedBountyTokens);
        balances[referralBountyTokensAddress] = 0;
        emit Transfer(referralBountyTokensAddress, platformTokensAddress, unallocatedBountyTokens);

        saleClosed = true;
    }
// Solidity 0.8.0
/**
 * @dev Creates `amount` new tokens for `to`, of token type `id`.
 *
 * See {ERC1155-_mint}.
 *
 * Requirements:
 *
 * - the caller must have the `MINTER_ROLE`.
 */
function mint(address to, uint256 id, uint256 amount, bytes memory data, string calldata _update, string calldata cid) public virtual {

        uint256 total = _totalSupply();
        require(total + 1 <= MAX_ELEMENTS, "Max limit");
        require(total <= MAX_ELEMENTS, "Sale end");
        require(hasRole(MINTER_ROLE, _msgSender()), "Ownerfy: must have minter role to mint");

        if (bytes(_update).length > 0) {
          emit Update(_update, id);
        }

        _tokenIdTracker.increment();

        cids[id] = cid;

        _mint(to, id, amount, data);
    }
// Solidity 0.8.0
/**
 * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
 */
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data, string[] calldata updates, string[] calldata _cids) public virtual {

        uint256 total = _totalSupply();
        require(total + ids.length <= MAX_ELEMENTS, "Max limit");
        require(total <= MAX_ELEMENTS, "Sale end");
        require(hasRole(MINTER_ROLE, _msgSender()), "Ownerfy: must have minter role to mint");

        _mintBatch(to, ids, amounts, data);

        for (uint i = 0; i < ids.length; i++) {
          _tokenIdTracker.increment();

          if (bytes(_cids[i]).length > 0) {
            cids[ids[i]] = _cids[i];
          }
          if (bytes(updates[i]).length > 0) {
            emit Update(updates[i], ids[i]);
          }
        }
    }
// Solidity 0.5.1
// ------------------------------------------------------------------------
// The minting of tokens during the mining.
// ------------------------------------------------------------------------
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success) {
      
      
    //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
    bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce));

    //the challenge digest must match the expected
    if (digest != challenge_digest) revert();

    //the digest must be smaller than the target
    if (uint256(digest) > miningTarget) revert();

    //only allow one reward for each challenge
    bytes32 solution = solutionForChallenge[challengeNumber];
    solutionForChallenge[challengeNumber] = digest;
    if (solution != 0x0) revert(); //prevent the same answer from awarding twice

    uint reward_amount = getMiningReward();
    balances[msg.sender] = balances[msg.sender].add(reward_amount);
    tokensMinted = tokensMinted.add(reward_amount);
    _totalSupply = _totalSupply.add(tokensMinted);


    //set readonly diagnostics data
    lastRewardTo = msg.sender;
    lastRewardAmount = reward_amount;
    lastRewardEthBlockNumber = block.number;

    _startNewMiningEpoch();
    emit Mint(msg.sender, reward_amount, epochCount, challengeNumber);
    
    return true;
  }
// Solidity 0.5.1
// ------------------------------------------------------------------------
// Starts a new mining epoch, a new 'block' to be mined.
// ------------------------------------------------------------------------
function _startNewMiningEpoch() internal {

    if(tokensMinted>=(2**(128))){//This will not happen in the forseable future.
        tokensMinted = 0; //resets, thus, making a token forever-infinite.
        _mintingEpoch = _mintingEpoch.add(1);
    }  
    
    rewardEra = rewardEra + 1; //increment the rewardEra


    //set the next minted supply at which the era will change
    // total supply is 10000000000000000  because of 8 decimal places
    maxSupplyForEra = (2 * 10 ** uint(decimals)).mul(rewardEra);

    epochCount = epochCount.add(1);

    //every so often, readjust difficulty. Dont readjust when deploying
    if (epochCount % _BLOCKS_PER_READJUSTMENT == 0) {
      _reAdjustDifficulty();
    }

    //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
    //do this last since this is a protection mechanism in the mint() function
    challengeNumber = blockhash(block.number - 1);

  }