lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/**
 * @dev Calculate investment details
 */
function calculateInvestment(address investor, uint value) public view
    returns (uint investment, uint tokensToSend, uint refundValue) {
    uint remainingInvestment = availableInvestment(investor);

    if (value <= remainingInvestment) {
      refundValue = 0;  
    } else {
      refundValue = value.sub(remainingInvestment);
    }

    investment = value.sub(refundValue);
    tokensToSend = investment.mul(rate).div(BASIS_POINTS_DEN);

    // if there are too few tokens remaining in supply
    if (tokensToSend > supply) {
      uint extraTokens = tokensToSend.sub(supply);
      tokensToSend = supply;
      refundValue += extraTokens.mul(BASIS_POINTS_DEN).div(rate);
      investment = value.sub(refundValue);
    }
  }
// Solidity 0.6.12
/**
 * @dev Invest into presale
 *
 * `investor` is sending ether and receiving tokens on `wallet` address and partial or full refund back on `invesor` address.
 */
function invest(address wallet) public payable whenRunning nonReentrant {
    address investor = _msgSender();

    require(isInvestor(investor), "Investor is not whitelisted");
    require(address(wallet) != address(0), "No wallet to transfer tokens to");
    require(msg.value > 0, "There's no value in transaction");
    require(supply > 0, "No remaining supply");
    
    (uint investment, uint tokensToSend, uint refundValue) = calculateInvestment(investor, msg.value);
    uint presaleTokenAllocation = token.balanceOf(address(this));

    require(presaleTokenAllocation >= tokensToSend, "Presale contract own less tokens than needed");
    require(investment > 0, "Zero amount for investment");

    supply -= tokensToSend;
    invested += investment;
    tokensSold += tokensToSend;
    investments[investor] += investment;
    receivedTokens[investor] += tokensToSend;
    refunds[investor] += refundValue;

    token.transfer(wallet, tokensToSend);
    treasury.transfer(investment);
    
    emit Invested(investor, wallet, msg.value, tokensToSend, refundValue);
  }
// Solidity 0.6.12
/**
 * @dev Update presale details
 */
function updateDetails(
    uint _startBlock,
    uint _endBlock,
    uint _endRefundBlock,
    uint _supply,
    uint _rate,
    uint _maxInvestment
  ) public onlyOwner {
    require(_endBlock > block.number, "End block must be greater than the current one");
    require(_endBlock > _startBlock, "Start block should be less than the end block");
    require(_endRefundBlock >= _endBlock, "Refund block must be greater than the end block");
    require(_rate > 0, "Rate must be greater than 0");
    require(_maxInvestment > 0, "Noone can invest nothing");
    
    startBlock = _startBlock;
    endBlock = _endBlock;
    endRefundBlock = _endRefundBlock;
    rate = _rate;
    maxInvestment = _maxInvestment;

    if (_supply > 0) {
      supply = _supply;
    }

    emit DetailsUpdated(_msgSender());
  }
// Solidity 0.8.4
// the current Form owner may always wield the metadata
function setMetaDesc(uint256 tokenId, string memory metadataDescription) public {
        require(_msgSender() == super.ownerOf(tokenId), "It is another's impression to make");
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        form[tokenId - 1].metaDesc = metadataDescription;
    }
// Solidity 0.8.4
// a subsequently immutable Form
function mintForm(string[17] memory line, string memory metadataDescription) public nonReentrant onlyOwner {
        require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && 
        bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && 
        bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&
        bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && 
        bytes(line[16]).length <= maxLineLen, string(abi.encodePacked("Each line may only contain ", toString(maxLineLen), " bytes")));
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        
        _safeMint(_msgSender(), getNumForm() + 1);
        addForm(Canvas(line, metadataDescription, true));
    }
// Solidity 0.8.4
/** one may paint a blank Canvas
 * with immutable ink
 * for history and the evolution of the collective consciousness */
function paintCanvas(uint256 tokenId, string[17] memory line, string memory metadataDescription) public nonReentrant {
        require(bytes(line[0]).length <= maxLineLen && bytes(line[1]).length <= maxLineLen && bytes(line[2]).length <= maxLineLen && bytes(line[3]).length <= maxLineLen && 
        bytes(line[4]).length <= maxLineLen && bytes(line[5]).length <= maxLineLen && bytes(line[6]).length <= maxLineLen && bytes(line[7]).length <= maxLineLen && 
        bytes(line[8]).length <= maxLineLen && bytes(line[9]).length <= maxLineLen && bytes(line[10]).length <= maxLineLen && bytes(line[11]).length <= maxLineLen &&
        bytes(line[12]).length <= maxLineLen && bytes(line[13]).length <= maxLineLen && bytes(line[14]).length <= maxLineLen && bytes(line[15]).length <= maxLineLen && 
        bytes(line[16]).length <= maxLineLen, string(abi.encodePacked("Each line may only contain ", toString(maxLineLen), " bytes")));
        require(bytes(metadataDescription).length <= maxMetaDescLen, string(abi.encodePacked("Metadata description may only contain ", toString(maxMetaDescLen), " bytes")));
        require(form[tokenId - 1].isPainted == false, "Form is no longer canvas");
        require(_msgSender() == super.ownerOf(tokenId), "It is another's impression to make");
        
        form[tokenId - 1].line = line;
        form[tokenId - 1].metaDesc = metadataDescription; 
        form[tokenId - 1].isPainted = true;
    }
// Solidity 0.5.0
// Function for buying shares
function buyShares(uint256 numberOfSharesToBuy) public whenNotPaused() returns (bool) {

        // Check that buying is enabled
        require(buyEnabled, "Buying is currenty disabled");
        require(numberOfSharesToBuy >= minVolume, "Volume too low");

        // Fetch the total price
        address buyer = msg.sender;
        uint256 sharesAvailable = getERC20Balance(ALEQContractAddress);
        uint256 totalPrice = getCumulatedPrice(numberOfSharesToBuy, sharesAvailable);

        // Check that there are enough shares
        require(sharesAvailable >= numberOfSharesToBuy, "Not enough shares available");

        //Check that XCHF balance is sufficient and allowance is set
        require(getERC20Available(XCHFContractAddress, buyer) >= totalPrice, "Payment not authorized or funds insufficient");

        // Compute usage fee and final payment amount
        uint256 usageFee = totalPrice.mul(usageFeeBSP).div(10000);
        uint256 paymentAmount = totalPrice.sub(usageFee);

        // Instantiate contracts
        ERC20 ALEQ = ERC20(ALEQContractAddress);
        ERC20 XCHF = ERC20(XCHFContractAddress);

        // Transfer usage fee and payment amount
        require(XCHF.transferFrom(buyer, usageFeeAddress, usageFee), "Usage fee transfer failed");
        require(XCHF.transferFrom(buyer, address(this), paymentAmount), "XCHF payment failed");

        // Transfer the shares
        require(ALEQ.transfer(buyer, numberOfSharesToBuy), "Share transfer failed");
        uint256 nextPrice = getCumulatedPrice(1, sharesAvailable.sub(numberOfSharesToBuy));
        emit SharesPurchased(buyer, numberOfSharesToBuy, totalPrice, nextPrice);
        return true;
    }
// Solidity 0.5.0
// Price getters
function getCumulatedPrice(uint256 amount, uint256 supply) public view returns (uint256){
        uint256 cumulatedPrice = 0;
        if (supply <= initialNumberOfShares) {
            uint256 first = initialNumberOfShares.add(1).sub(supply);
            uint256 last = first.add(amount).sub(1);
            cumulatedPrice = helper(first, last);
        }

        else if (supply.sub(amount) >= initialNumberOfShares) {
            cumulatedPrice = minPriceInXCHF.mul(amount);
        }

        else {
            cumulatedPrice = supply.sub(initialNumberOfShares).mul(minPriceInXCHF);
            uint256 first = 1;
            uint256 last = amount.sub(supply.sub(initialNumberOfShares));
            cumulatedPrice = cumulatedPrice.add(helper(first,last));
        }
        
        return cumulatedPrice;
    }
// Solidity 0.4.17
// Crowdsale  {constructor}
// @notice fired when contract is crated. Initilizes all constnat and initial values.
function Crowdsale(WhiteList _whiteListAddress) public {
        multisig = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88; 
        team = 0x49447Ea549CCfFDEF2E9a9290709d6114346df88;                                         
        startBlock = 0; // Should wait for the call of the function start
        endBlock = 0; // Should wait for the call of the function start                  
        tokenPriceWei = 108110000000000;
        maxCap = 210000000e18;         
        minCap = 21800000e18;        
        totalTokensSent = 0;  //TODO: add tokens sold in private sale
        setStep(Step.FundingPreSale);
        numOfBlocksInMinute = 416;    
        whiteList = WhiteList(_whiteListAddress);    
        teamTokens = 45000000e18;
    }
// Solidity 0.4.17
// @notice set the step of the campaign 
// @param _step {Step}
function setStep(Step _step) public onlyOwner() {
        currentStep = _step;
        
        if (currentStep == Step.FundingPreSale) {  // for presale 
          
            minInvestETH = 1 ether/5;                             
        }else if (currentStep == Step.FundingPublicSale) { // for public sale           
            minInvestETH = 1 ether/10;               
        }      
    }
// Solidity 0.4.17
// @notice Due to changing average of block time
// this function will allow on adjusting duration of campaign closer to the end 
function adjustDuration(uint _block) external onlyOwner() {

        require(_block < 389376);  // 4.16*60*24*65 days = 389376     
        require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past
        endBlock = startBlock.add(_block); 
    }
// Solidity 0.4.17
// @notice determine if purchase is valid and return proper number of tokens
// @return tokensToSend {uint} proper number of tokens based on the timline     
function determinePurchase() internal view  returns (uint) {
       
        require(msg.value >= minInvestETH);                        // ensure that min contributions amount is met  
        uint tokenAmount = msg.value.mul(1e18) / tokenPriceWei;    // calculate amount of tokens

        uint tokensToSend;  

        if (currentStep == Step.FundingPreSale)
            tokensToSend = calculateNoOfTokensToSend(tokenAmount); 
        else
            tokensToSend = tokenAmount;
                                                                                                       
        return tokensToSend;
    }
// Solidity 0.4.17
// @notice This function will return number of tokens based on time intervals in the campaign
// @param _tokenAmount {uint} amount of tokens to allocate for the contribution
function calculateNoOfTokensToSend(uint _tokenAmount) internal view  returns (uint) {
              
        if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 14) / 100)        // less equal then/equal 14 days
            return  _tokenAmount + (_tokenAmount * 40) / 100;  // 40% bonus
        else if (block.number <= startBlock + (numOfBlocksInMinute * 60 * 24 * 28) / 100)   // less equal  28 days
            return  _tokenAmount + (_tokenAmount * 30) / 100; // 30% bonus
        else
            return  _tokenAmount + (_tokenAmount * 20) / 100;   // remainder of the campaign 20% bonus
          
    }
// Solidity 0.4.17
// @notice called to send tokens to contributors after ICO and lockup period. 
// @param _backer {address} address of beneficiary
// @return true if successful
function claimTokensForUser(address _backer) internal returns(bool) {       

        require(currentStep == Step.Claiming);
                  
        Backer storage backer = backers[_backer];

        require(!backer.refunded);      // if refunded, don't allow for another refund           
        require(!backer.claimed);       // if tokens claimed, don't allow refunding            
        require(backer.tokensToSend != 0);   // only continue if there are any tokens to send           

        claimCount++;
        claimed[_backer] = backer.tokensToSend;  // save claimed tokens
        backer.claimed = true;
        totalClaimed += backer.tokensToSend;
        
        if (!token.transfer(_backer, backer.tokensToSend)) 
            revert(); // send claimed tokens to contributor account

        TokensClaimed(_backer, backer.tokensToSend);  
    }
// Solidity 0.4.17
// @notice it will allow contributors to get refund in case campaign failed
function refund() external stopInEmergency returns (bool) {

        require(currentStep == Step.Refunding);         
       
        require(this.balance > 0);  // contract will hold 0 ether at the end of campaign.                                  
                                    // contract needs to be funded through fundContract() 

        Backer storage backer = backers[msg.sender];

        require(backer.weiReceived > 0);  // esnure that user has sent contribution
        require(!backer.refunded);         // ensure that user hasn't been refunded yet
        require(!backer.claimed);       // if tokens claimed, don't allow refunding   
       
        backer.refunded = true;  // save refund status to true
    
        refundCount++;
        totalRefunded = totalRefunded.add(backer.weiReceived);
        msg.sender.transfer(backer.weiReceived);  // send back the contribution 
        RefundETH(msg.sender, backer.weiReceived);
        return true;
    }
// Solidity 0.4.19
/// Create a new Lotto
function LottoCount() public 
    {
        worldOwner = msg.sender; 
        
        ticketPrice = 0.0101 * 10**18;
        maxTickets = 10;
        
		_direction = 0;
        lottoIndex = 1;
        lastTicketTime = 0;
        
        numtickets = 0;
        totalBounty = 0;
    }
// Solidity 0.8.9
// Deposits ore to be burned
function burnOre(uint256 _amount) external nonReentrant {
    require(_openForBurning, "Not Open For Burning");
    require(_amount > 0, "Invalid Ore Amount");
    require(ore.balanceOf(msg.sender) >= _amount, "Insufficient Ore");

    ore.burn(msg.sender, _amount);

    _burntOreByAddress[msg.sender][_currentLaunch] += _amount;
    _totalBurntOreByLaunch[_currentLaunch] += _amount;
  }
// Solidity 0.8.9
// Calculates and returns the total amount of claimable funds for the specified account and period
function totalClaimableByAccount(
    address _account,
    uint256 _fromLaunch,
    uint256 _toLaunch
  ) public view returns (
    uint256,
    uint256[] memory
  ) {
    require(_fromLaunch > 0 && _toLaunch <= _currentLaunch && _fromLaunch <= _toLaunch, "Invalid Launch Period");

    // Calculate the total claimable amount along with the detail for each launch in the specified period range
    uint256 totalClaimable = 0;
    uint256 periodSize = _toLaunch - _fromLaunch + 1;
    uint256[] memory maxPerLaunch = new uint256[](periodSize);
    for (uint256 i = _fromLaunch; i <= _toLaunch ; i++) {
      uint256 maxAmount = 0;

      if (_totalBurntOreByLaunch[i] > 0 && _totalFundsByLaunch[i] > 0) {
        maxAmount = (_burntOreByAddress[_account][i] * _totalFundsByLaunch[i]) / _totalBurntOreByLaunch[i];
        uint256 claimable = maxAmount - _claimedByAddress[_account][i];

        if (claimable > 0) {
          totalClaimable += claimable;
        }
      }

      uint256 index = i - _fromLaunch;
      maxPerLaunch[index] = maxAmount;
    }

    return (totalClaimable, maxPerLaunch);
  }
// Solidity 0.8.9
// Can be called by collectors for claiming funds from the ore burning mechanism
function claim(uint256 _fromLaunch, uint256 _toLaunch) external nonReentrant {
    uint256 totalClaimable;
    uint256[] memory maxPerLaunch;
    (totalClaimable, maxPerLaunch) = totalClaimableByAccount(msg.sender, _fromLaunch, _toLaunch);

    // Check the claimable amount and update the total claimed so far for the account
    require(totalClaimable > 0, "Insufficient Claimable Funds");
    for (uint256 i = _fromLaunch; i <= _toLaunch; i++) {
      uint256 index = i - _fromLaunch;
      if (_claimedByAddress[msg.sender][i] < maxPerLaunch[index]) {
        _claimedByAddress[msg.sender][i] = maxPerLaunch[index];
      }
    }

    payable(msg.sender).transfer(totalClaimable);
  }
// Solidity 0.8.9
// Handles funds received for the pool
receive() external payable {
    // Make sure enough funds are sent, and the source is whitelisted
    require(msg.value > 0, "Insufficient Funds");
    require(fundAddresses[msg.sender], "Invalid Fund Address");

    // Update the total received funds for the currently open launch
    _totalFundsByLaunch[_currentLaunch] += msg.value;
  }
// Solidity 0.4.24
/* function registerNameXID(string _nameString, uint256 _affCode, bool _all)
 isHuman()
 public
 payable
 {
 bytes32 _name = _nameString.nameFilter();
 address _addr = msg.sender;
 uint256 _paid = msg.value;
 (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
 
 uint256 _pID = pIDxAddr_[_addr];
 
 // fire event
 emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
 } */
function registerNameXaddr(string _nameString, address _affCode, bool _all)
          isHuman()
          public
          payable
      {
          bytes32 _name = _nameString.nameFilter();
          address _addr = msg.sender;
          uint256 _paid = msg.value;
          (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);

          uint256 _pID = pIDxAddr_[_addr];

          // fire event
          emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
      }
// Solidity 0.5.12
// An internal convenience function that checks to see if we are currently
// in the Window defined by the WindowParameters struct passed as an
// argument.
function _isInWindow(WindowParameters memory localParams) internal view returns (bool) {
        // We are never "in a window" if the contract is paused
        if (block.number < localParams.pauseEndedBlock) {
            return false;
        }

        // If we are before the first window of this type, we are obviously NOT
        // in this window!
        if (block.number < localParams.firstWindowStartBlock) {
            return false;
        }

        // Use modulus to figure out how far we are past the beginning of the
        // most recent window
        // of this type
        uint256 windowOffset = (block.number - localParams.firstWindowStartBlock) % localParams.sessionDuration;

        // If we are in the window, we will be within duration of the start of
        // the most recent window
        return windowOffset < localParams.windowDuration;
    }
// Solidity 0.5.12
/// @notice A getter function for determining whether we are currently in a
///  fightWindow for a given tournament
/// @param _basicTournamentAddress  The address of the tournament in
///  question
/// @return  Whether or not we are in a fightWindow for this tournament
function _isInFightWindowForTournament(address _basicTournamentAddress) internal view returns (bool){
        uint256 tournamentStartBlock;
        uint256 pauseEndedBlock;
        uint256 admissionDuration;
        uint256 duelTimeoutDuration;
        uint256 ascensionWindowDuration;
        uint256 fightWindowDuration;
        uint256 cullingWindowDuration;
        (
            tournamentStartBlock,
            pauseEndedBlock,
            admissionDuration,
            ,
            duelTimeoutDuration,
            ,
            ascensionWindowDuration,
            ,
            fightWindowDuration,
            ,
            ,
            ,
            cullingWindowDuration
        ) = IBasicTournamentTimeParams(_basicTournamentAddress).getTimeParameters();
        uint256 firstSessionStartBlock = uint256(tournamentStartBlock) + uint256(admissionDuration);
        uint256 sessionDuration = uint256(ascensionWindowDuration) + uint256(fightWindowDuration) + uint256(duelTimeoutDuration) + uint256(cullingWindowDuration);

        return _isInWindow(WindowParameters({
            firstWindowStartBlock: uint48(uint256(firstSessionStartBlock) + uint256(ascensionWindowDuration)),
            pauseEndedBlock: uint48(pauseEndedBlock),
            sessionDuration: uint32(sessionDuration),
            windowDuration: uint32(fightWindowDuration)
        }));
    }
// Solidity 0.5.12
/// @notice A seller/maker calls this function to update the pricePerPower
///  of an order that they already have stored in this contract. This saves
///  some gas for the seller by allowing them to just update the
///  pricePerPower parameter of their order.
/// @param _wizardId  The tokenId for the seller's wizard. This is the
///  wizard that will relinquish its power if an order is fulfilled.
/// @param _newPricePerPower  An order creator specifies how much wei they
///  are willing to sell their wizard's power for. Note that this price is
///  per-power, so the buyer will actually have to pay this price
///  multiplied by the amount of power that the wizard has.
/// @param _basicTournamentAddress  The address of the tournament that this
///  order pertains to. Note that each Wizard has an independent power
///  value for each tournament, and call sell each one separately, so
///  orders can exist simultaneously for the same wizard for different
///  tournaments.
function updateSellOrder(uint256 _wizardId, uint256 _newPricePerPower, address _basicTournamentAddress) external whenNotPaused nonReentrant {
        require(WizardGuild(wizardGuildAddress).ownerOf(_wizardId) == msg.sender, 'only the owner of the wizard can update a sell order');
        require(WizardGuild(wizardGuildAddress).isApprovedOrOwner(address(this), _wizardId), 'you must call the approve() function on WizardGuild before you can update a sell order');
        require(_newPricePerPower <= uint256(~uint128(0)), 'you cannot specify a _newPricePerPower greater than uint128_max');

        // Fetch order
        Order storage order = orderForWizardIdAndTournamentAddress[_basicTournamentAddress][_wizardId];

        // Check that order is not from a previous owner
        require(msg.sender == order.makerAddress, 'you can only update a sell order that you created');

        // Emit event
        emit UpdateSellOrder(
            _wizardId,
            uint256(order.pricePerPower),
            _newPricePerPower,
            msg.sender,
            _basicTournamentAddress,
            uint256(order.savedSuccessfulTradeFeeInBasisPoints)
        );

        // Update price
        order.pricePerPower = uint128(_newPricePerPower);
    }