lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/* @dev Redeem a specific token from the pool.
 * Fee will be incured.  Will incur penalty if the pool is unbalanced.
 */
function redeem(
        uint256 bTokenIdx,
        uint256 bTokenAmount,
        uint256 lpTokenBurnedMax
    )
        external
        nonReentrantAndUnpausedV1
    {
        require(bTokenAmount > 0, "Amount must be greater than 0");

        uint256 info = _tokenInfos[bTokenIdx];
        require (info != 0, "Backed token is not found!");

        // Obtain normalized balances.
        // Gas saving: Use cached balances/totalBalance without accrued interest since last rebalance.
        (
            uint256[] memory balances,
            uint256[] memory softWeights,
            uint256[] memory hardWeights,
            uint256 totalBalance
        ) = _getBalancesAndWeights();
        uint256 bTokenAmountNormalized = bTokenAmount.mul(_normalizeBalance(info));
        require(balances[bTokenIdx] >= bTokenAmountNormalized, "Insufficient token to redeem");

        _collectReward(totalBalance);

        uint256 lpAmount = bTokenAmountNormalized.add(
            _redeemPenaltyForAll(
                bTokenIdx,
                totalBalance,
                balances,
                softWeights,
                hardWeights,
                bTokenAmountNormalized
            )).mul(totalSupply()).div(totalBalance);
        require(lpAmount <= lpTokenBurnedMax, "burned token should <= maximum lpToken offered");

        _burn(msg.sender, lpAmount);

        /* Transfer out the token after deducting the fee.  Rebalance cash reserve if needed */
        uint256 fee = bTokenAmount.mul(_redeemFee).div(W_ONE);
        _transferOut(
            _tokenInfos[bTokenIdx],
            bTokenAmount.sub(fee),
            fee.mul(_adminFeePct).div(W_ONE)
        );

        emit Redeem(msg.sender, bTokenAmount, lpAmount);
    }
// Solidity 0.6.12
/*
 * @dev Swap a token to another.
 * @param bTokenIdIn - the id of the token to be deposited
 * @param bTokenIdOut - the id of the token to be withdrawn
 * @param bTokenInAmount - the amount (unnormalized) of the token to be deposited
 * @param bTokenOutMin - the mininum amount (unnormalized) token that is expected to be withdrawn
 */
function swap(
        uint256 bTokenIdxIn,
        uint256 bTokenIdxOut,
        uint256 bTokenInAmount,
        uint256 bTokenOutMin
    )
        external
        nonReentrantAndUnpausedV1
    {
        uint256 infoIn = _tokenInfos[bTokenIdxIn];
        uint256 infoOut = _tokenInfos[bTokenIdxOut];
        (
            uint256 bTokenOutAmount,
            uint256 adminFee
        ) = _getSwapAmount(infoIn, infoOut, bTokenInAmount);
        require(bTokenOutAmount >= bTokenOutMin, "Returned bTokenAmount < asked");

        _transferIn(infoIn, bTokenInAmount);
        _transferOut(infoOut, bTokenOutAmount, adminFee);

        emit Swap(
            msg.sender,
            bTokenIdxIn,
            bTokenIdxOut,
            bTokenInAmount,
            bTokenOutAmount
        );
    }
// Solidity 0.5.17
/**
 * @notice Convert uint256 to string
 * @param _i Unsigned integer to convert to string
 */
function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
    if (_i == 0) {
      return "0";
    }

    uint256 j = _i;
    uint256 ii = _i;
    uint256 len;

    // Get number of bytes
    while (j != 0) {
      len++;
      j /= 10;
    }

    bytes memory bstr = new bytes(len);
    uint256 k = len - 1;

    // Get each individual ASCII
    while (ii != 0) {
      bstr[k--] = byte(uint8(48 + ii % 10));
      ii /= 10;
    }

    // Convert to string
    return string(bstr);
  }
// Solidity 0.5.17
/**
 * @notice Mint _amount of tokens of a given id
 * @param _to      The address to mint tokens to
 * @param _id      Token id to mint
 * @param _amount  The amount to be minted
 * @param _data    Data to pass if receiver is contract
 */
function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data)
    internal
  {
    // Add _amount
    balances[_to][_id] = balances[_to][_id].add(_amount);

    // Emit event
    emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount);

    // Calling onReceive method if recipient is contract
    _callonERC1155Received(address(0x0), _to, _id, _amount, _data);
  }
// Solidity 0.5.17
/**
 * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair
 * @param _from     The address to burn tokens from
 * @param _ids      Array of token ids to burn
 * @param _amounts  Array of the amount to be burned
 */
function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts)
    internal
  {
    require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH");

    // Number of mints to execute
    uint256 nBurn = _ids.length;

     // Executing all minting
    for (uint256 i = 0; i < nBurn; i++) {
      // Update storage balance
      balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]);
    }

    // Emit batch mint event
    emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts);
  }
// Solidity 0.5.17
/**
 	 * @dev Creates a new token type and assigns _initialSupply to an address
 	 * @param _maxSupply max supply allowed
 	 * @param _initialSupply Optional amount to supply the first owner
 	 * @param _data Optional data to pass if receiver is contract
 	 * @return The newly created token ID
 	 */
function create(
		uint256 _maxSupply,
		uint256 _initialSupply,
		bytes calldata _data
	) external onlyWhitelistAdmin returns (uint256 tokenId) {
		require(_initialSupply <= _maxSupply, "ERC1155Tradable#create: Initial supply cannot be more than max supply");
		uint256 _id = _getNextTokenID();
		_incrementTokenTypeId();
		creators[_id] = msg.sender;

    if (bytes(baseMetadataURI).length > 0) {
      _logURI(_id);
    }

		if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
		tokenSupply[_id] = _initialSupply;
		tokenMaxSupply[_id] = _maxSupply;
		return _id;
	}
// Solidity 0.5.17
/**
 	 * @dev Mints some amount of tokens to an address
 	 * @param _to          Address of the future owner of the token
 	 * @param _id          Token ID to mint
 	 * @param _quantity    Amount of tokens to mint
 	 * @param _data        Data to pass if receiver is contract
 	 */
function mint(
		address _to,
		uint256 _id,
		uint256 _quantity,
		bytes memory _data
	) public onlyMinter {
    require(_exists(_id), "ERC1155Tradable#mint: NONEXISTENT_TOKEN");
    require(_to != address(0), "ERC1155Tradable#mint: INVALID_RECIPIENT");
		require(tokenSupply[_id].add(_quantity) <= tokenMaxSupply[_id], "ERC1155Tradable#mint: mint supply cannot be more than max supply");

		_mint(_to, _id, _quantity, _data);
		tokenSupply[_id] = tokenSupply[_id].add(_quantity);
	}
// Solidity 0.5.17
/**
 	 * @dev Burns some amount of tokens from an address
 	 * @param _from        Address of the owner of the token
 	 * @param _id          Token ID to burn
 	 * @param _quantity    Amount of tokens to burn
 	 */
function burn(address _from, uint256 _id, uint256 _quantity) public {
    require(_exists(_id), "ERC1155Tradable#burn: NONEXISTENT_TOKEN");
    require(_from == _msgSender() || isApprovedForAll(_from, _msgSender()), "ERC1155Tradable#burn: caller is not owner nor approved");

    _burn(_from, _id, _quantity);
    tokenSupply[_id] = tokenSupply[_id].sub(_quantity);
  }
// Solidity 0.5.12
// for upgrade, reset the attributes of ranch
function ranch(uint totalSheepPrice, uint sheepNum) public view onlyForCryptoRanch returns(uint, uint, uint, uint) {
        uint ranchGrade = getRanchGrade(sheepNum);
        uint ranchSize = getRanchSize(ranchGrade);
        uint admissionPrice = getAdmissionPrice(totalSheepPrice);
        uint maxProfitability = getMaxProfitability(ranchGrade, admissionPrice);

        return (
        ranchGrade,
        ranchSize,
        admissionPrice,
        maxProfitability
        );
    }
// Solidity 0.5.12
// Cancel sell order
function cancelSellOrder(uint sellerID) public onlyForCryptoRanch {
        require(isFleshUp == false, "isFleshUp");
        // id check
        uint orderID = orderIDByPID[sellerID];
        require(orderID > 0 && sellOrders.length >= orderID, "Id error!");
        // owner check
        Order storage order = sellOrders[orderID];
        require(order.ownerID == sellerID, "no exist");

        if (global.sheepPrice == 99 finney && order.sheepPrice == 50 finney) {
            revert("0.099 not allowed cancel 0.1 eth order");
        }

        uint tmpPrice = order.sheepPrice;
        // normalize sheep number
        uint tmpSheepNum = order.sheepNum.mul(2**(cryptoRanch.getReproductionRound().sub(order.round)));
        delete sellOrders[orderID];

        cryptoRanch.addSheepNumber(sellerID, tmpSheepNum, 0, false);
        usrPriceSheepNum[tmpPrice] = usrPriceSheepNum[tmpPrice].sub(tmpSheepNum);

        orderIDByPID[sellerID] = 0;

        emit OnOrderCancel(cryptoRanch.getAddrByPID(sellerID), tmpSheepNum, now);
    }
// Solidity 0.5.12
// find the next price which has sheep
function determineForwardSheepPrice(uint start) private {
        for (uint i =  start; i < 100 finney; i = i.add(1 finney)) {
            if (sysPriceSheepNum[i] > 0 || usrPriceSheepNum[i] > 0) {
                global.sheepPrice = i;
                return;
            }
        }
    }
// Solidity 0.5.12
/* reproduce */
function reproductionStage() private {
        // double the sheep & renew the price interval
        global.sheepNum = global.sheepNum.mul(2);
        global.sysInSaleNum = global.sysInSaleNum.mul(2);
        global.sheepPrice = 50 finney;
        global.sysSoldNum = 0;
        priceCumulativeCount = 56 finney;
        isFleshUp = false;

        uint addSheepNum = global.sysInSaleNum.div(50);
        uint j = 1;

        global.priceInterval[0] = 50 finney;

        for (uint i = 51 finney; i <= 98 finney; i=i.add(1 finney)) { //99 price just sold out
            // double the remaining sheep on the price in range of 51 ~ 98
            // 50 price has setup before the reproduction
            if (sysPriceSheepNum[i] > 0) sysPriceSheepNum[i] = sysPriceSheepNum[i].mul(2);
            if (usrPriceSheepNum[i] > 0) usrPriceSheepNum[i] = usrPriceSheepNum[i].mul(2);
            // renew the price interval
            if (j <= 6) {
                sysPriceSheepNum[i] = sysPriceSheepNum[i].add(addSheepNum);
                global.priceInterval[j] = i;
                j++;
            }
        }

        cryptoRanch.addReproductionRound();
        reproductionBlkNums.push(block.number);

        emit OnPriceChange(global.sheepPrice, now);
    }
// Solidity 0.5.12
// a function that allows owner to add
function firstGenerationJoinGame(uint sheepNum) payable public isHuman() isValidSheepNum(sheepNum){
        require(whiteList[msg.sender] == true, 'Invalid user');
        require(pIDByAddr[msg.sender] == 0, 'Player has joined!');

        uint buyerID = makePlayerID(msg.sender);
        uint balance = msg.value;

        usrBook[buyerID].isFirstGeneration = true;
        emit OnFirstGenerationJoinGame(msg.sender, sheepNum, balance, now);

        initRanchData(buyerID, sheepNum);

        txSystem.buySheepFromOrders(buyerID, balance, sheepNum, false);
        initSalesData(buyerID, usrLastTotalCost[buyerID]);
    }
// Solidity 0.5.12
// player purchase sheep via the operating capital
function rebuyForSheep(uint sheepNum, uint value) isHuman() playerIsAlive() public{
        uint buyerID = pIDByAddr[msg.sender];
        require(usrBook[buyerID].rebuy >= value, "Invalid rebuy value!");

        uint balance = usrBook[buyerID].isFirstGeneration? value : value.div(2);

        txSystem.buySheepFromOrders(buyerID, balance, sheepNum, true);
        uint actualRebuy = usrBook[buyerID].isFirstGeneration? usrLastTotalCost[buyerID] : usrLastTotalCost[buyerID].mul(2);
        usrBook[buyerID].rebuy = usrBook[buyerID].rebuy.sub(actualRebuy);

        emit OnReBuy(usrBook[buyerID].addr, sheepNum, actualRebuy, now);
    }
// Solidity 0.5.12
// Add new sale order to the contract
function addNewSellOrder(uint sheepNum,  uint sheepPrice) isHuman() playerIsAlive() public {
        uint sellerID = pIDByAddr[msg.sender];
        require(sheepNum > 0, "Not allow zero sheep number");
        require(sheepPrice % (1 finney) == 0, "Illegal price");
        // normalize the sheep number of seller
        normalizeSheepNum(sellerID);

        //the max sheep of order can't exceed the 10% global sheep
        uint quo = usrBook[sellerID].sheepNum.div(10);
        uint rem = usrBook[sellerID].sheepNum % 10;
        if (rem > 0) quo = quo.add(1);
        require(usrBook[sellerID].sheepNum >= sheepNum && sheepNum <= quo, "Unmatched available sell sheep number!");

        // the accumulated profit can't exceed the max production capacity of ranch
        require(usrBook[sellerID].accumulatedProfits.add(sheepNum.mul(sheepPrice)) <= usrBook[sellerID].maxProfitability.div(1000),
            "exceed number to sale");

        // new sell-order process
        txSystem.addNewSellOrder(sellerID, sheepNum, sheepPrice);
    }
// Solidity 0.5.12
// player base ranch data setup
function initRanchData(uint pID, uint sheepNum) internal{
        usrBook[pID].ranchGrade = ranch.getRanchGrade(sheepNum);
        usrBook[pID].ranchSize = ranch.getRanchSize(usrBook[pID].ranchGrade);
        // grade 0 is invalid for upgrade
        if(usrBook[pID].ranchSize == 0) {
            usrBook[pID].status = PlayerStatus.OVERLOADED;
        } else {
            usrBook[pID].status = PlayerStatus.NORMAL;
        }
        usrBook[pID].weekRound = globalWeekRound;
        usrBook[pID].weekSheepCount = 0;
        usrBook[pID].round = reproductionRound;
        usrBook[pID].joinRound = reproductionRound;
        usrBook[pID].profit = 0;
    }
// Solidity 0.5.12
//renew the week rank data and sort list
function reorderWeekRank(uint pID, uint sheepNum) private {
        // renew the enrolled number
        usrBook[pID].weekSheepCount = usrBook[pID].weekSheepCount.add(sheepNum);

        bool tmpJudge = false;
        int index = -1;
        for(uint i = 0; i < 3; i ++) {
            if (usrBook[pID].weekSheepCount > usrBook[weekRank[i]].weekSheepCount) {
                index = int(i); // record the biggest rank-index of less count
                if (tmpJudge) {
                    uint tmpID = weekRank[i];
                    weekRank[i] = pID;
                    weekRank[i-1] = tmpID;
                }
            }
            if (pID == weekRank[i]) tmpJudge = true; // check whether already on list
        }

        if (tmpJudge == false) {
            for(uint i = 0; int(i) <= index; i++) {
                uint tmpID = weekRank[i];
                weekRank[i] = pID;
                if (i != 0) weekRank[i-1] = tmpID;
            }
        }
    }
// Solidity 0.5.12
//Add sheep number of buyer (called from transaction system)
function addSheepNumber(uint pID, uint sheepNum, uint totalCost, bool isBuy) external onlyForTxSystem(){
        // normalize sheep number,
        normalizeSheepNum(pID);

        usrBook[pID].sheepNum = usrBook[pID].sheepNum.add(sheepNum);
        usrLastTotalCost[pID] = totalCost;
        emit OnAddSheepNumber(usrBook[pID].addr, sheepNum, totalCost, now);

        // if it's a cancel order or buy
        if(isBuy && usrBook[pID].isFirstGeneration == false) {
            // distribute commission
            distributeCommission(pID, totalCost);
        }
    }
// Solidity 0.5.12
// revenue setting, including 60% profit and 40% operating capital
function processSellerProfit(uint pID, uint revenue) external onlyForTxSystem(){
        if (pID == 0) {
            ghostProfit = ghostProfit.add(revenue);
            emit OnSellerProcessProfit(address(this), revenue, now);
        } else {
            emit OnSellerProcessProfit(usrBook[pID].addr, revenue, now);
            // preprocess to determine whether overload
            addAccumulatedValue(pID, revenue);
            // sales profit
            uint tmpProfit = revenue.mul(60).div(100);
            usrBook[pID].profit = usrBook[pID].profit.add(tmpProfit);

            // operating capital
            uint tmpRebuy = revenue.sub(tmpProfit);
            if (usrBook[pID].status == PlayerStatus.NORMAL) {
                usrBook[pID].rebuy = usrBook[pID].rebuy.add(tmpRebuy);
            } else {
                ghostProfit = ghostProfit.add(tmpRebuy);
            }
        }
    }
// Solidity 0.5.12
// add revenue to accumulated profit, determine whether the ranch is overload
function addAccumulatedValue(uint pID, uint revenue) private{
        //for test
        //emit OnSellerProcessProfit(usrBook[pID].addr, revenue, now);

        usrBook[pID].accumulatedProfits = usrBook[pID].accumulatedProfits.add(revenue);
        if (usrBook[pID].status != PlayerStatus.OVERLOADED && usrBook[pID].accumulatedProfits >= usrBook[pID].maxProfitability.div(1000)) {
            usrBook[pID].status = PlayerStatus.OVERLOADED;

            txSystem.burnSheepGlobal(usrBook[pID].sheepNum);

            ghostProfit = ghostProfit.add(usrBook[pID].rebuy);
            usrBook[pID].rebuy = 0;
        }
    }
// Solidity 0.6.12
/**
 * @notice Transfer tokens to multiple recipient
 * @dev Left 160 bits are the recipient address and the right 96 bits are the token amount.
 * @param bits array of uint
 * @return true/false
 */
function multiTransfer(uint256[] memory bits) external returns (bool) {
        for (uint256 i = 0; i < bits.length; i++) {
            address a = address(bits[i] >> 96);
            uint256 amount = bits[i] & ((1 << 96) - 1);
            require(transfer(a, amount), "Transfer failed");
        }
        return true;
    }
// Solidity 0.6.12
/// @dev Overridden ERC20 transferFrom
function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(
            sender,
            _msgSender(),
            allowance(sender, _msgSender()).sub(
                amount,
                "VSP::transferFrom: transfer amount exceeds allowance"
            )
        );
        _moveDelegates(delegates[sender], delegates[recipient], amount);
        return true;
    }
// Solidity 0.8.4
//Disburse and End the staking pool
function disburseAndEnd(uint _finalDisburseAmount) public onlyOwner returns (bool){
        require(!ended, "Staking already ended");
        require(_finalDisburseAmount > 0);
        
        address _hold;
        uint _add;
        for(uint i = 0; i < holders.length(); i = i.add(1)){
            _hold = holders.at(i);
            _add = depositedTokens[_hold].mul(_finalDisburseAmount).div(totalDeposited);
            pending[_hold] = pending[_hold].add(_add);
        }
        totalDisbursed = totalDisbursed.add(_finalDisburseAmount);
        
        ended = true;
        return true;
    }
// Solidity 0.8.4
/*
 function withdrawAllAfterEnd() public {
 require(ended, "Staking has not ended");
 
 uint _pend = pending[msg.sender];
 uint amountToWithdraw = _pend.add(depositedTokens[msg.sender]);
 
 require(amountToWithdraw >= 0, "Invalid amount to withdraw");
 pending[msg.sender] = 0;
 depositedTokens[msg.sender] = 0;
 totalDeposited = totalDeposited.sub(depositedTokens[msg.sender]);
 require(Token(tokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens.");
 
 totalClaimedRewards = totalClaimedRewards.add(_pend);
 totalEarnedTokens[msg.sender] = totalEarnedTokens[msg.sender].add(_pend);
 
 holders.remove(msg.sender);
 
 }*/
function getStakersList(uint startIndex, uint endIndex) 
        public 
        view 
        returns (address[] memory stakers, 
            uint[] memory stakingTimestamps, 
            uint[] memory lastClaimedTimeStamps,
            uint[] memory stakedTokens) {
        require (startIndex < endIndex);
        
        uint length = endIndex.sub(startIndex);
        address[] memory _stakers = new address[](length);
        uint[] memory _stakingTimestamps = new uint[](length);
        uint[] memory _lastClaimedTimeStamps = new uint[](length);
        uint[] memory _stakedTokens = new uint[](length);
        
        for (uint i = startIndex; i < endIndex; i = i.add(1)) {
            address staker = holders.at(i);
            uint listIndex = i.sub(startIndex);
            _stakers[listIndex] = staker;
            _stakedTokens[listIndex] = depositedTokens[staker];
        }
        
        return (_stakers, _stakingTimestamps, _lastClaimedTimeStamps, _stakedTokens);
    }
// Solidity 0.4.19
/**
 * @dev Give a mint delegate permission to mint tokens.
 * @param _mintDelegate The account to be approved.
 */
function approveMintDelegate(address _mintDelegate) onlyOwner public returns (bool) {
    bool delegateFound = false;
    for(uint i=0; i<mintDelegates.length; i++) {
      if(mintDelegates[i]==_mintDelegate) {
        delegateFound = true;
        break;
      }
    }

    if(!delegateFound) {
      mintDelegates.push(_mintDelegate);
    }

    ApproveMintDelegate(_mintDelegate);
    return true;
  }
// Solidity 0.4.19
/**
 * @dev Revoke permission to mint tokens from a mint delegate.
 * @param _mintDelegate The account to be revoked.
 */
function revokeMintDelegate(address _mintDelegate) onlyOwner public returns (bool) {
    uint length = mintDelegates.length;
    require(length > 0);

    address lastDelegate = mintDelegates[length-1];
    if(_mintDelegate == lastDelegate) {
      delete mintDelegates[length-1];
      mintDelegates.length--;
    }
    else {
      // Game plan: find the delegate, replace it with the very last item in the array, then delete the last item
      for(uint i=0; i<length; i++) {
        if(mintDelegates[i]==_mintDelegate) {
          mintDelegates[i] = lastDelegate;
          delete mintDelegates[length-1];
          mintDelegates.length--;
          break;
        }
      }
    }

    RevokeMintDelegate(_mintDelegate);
    return true;
  }
// Solidity 0.4.19
/**
 * @dev Give a burn delegate permission to burn tokens.
 * @param _burnDelegate The account to be approved.
 */
function approveBurnDelegate(address _burnDelegate) onlyOwner public returns (bool) {
    bool delegateFound = false;
    for(uint i=0; i<burnDelegates.length; i++) {
      if(burnDelegates[i]==_burnDelegate) {
        delegateFound = true;
        break;
      }
    }

    if(!delegateFound) {
      burnDelegates.push(_burnDelegate);
    }

    ApproveBurnDelegate(_burnDelegate);
    return true;
  }
// Solidity 0.4.19
/**
 * @dev Revoke permission to burn tokens from a burn delegate.
 * @param _burnDelegate The account to be revoked.
 */
function revokeBurnDelegate(address _burnDelegate) onlyOwner public returns (bool) {
    uint length = burnDelegates.length;
    require(length > 0);

    address lastDelegate = burnDelegates[length-1];
    if(_burnDelegate == lastDelegate) {
      delete burnDelegates[length-1];
      burnDelegates.length--;
    }
    else {
      // Game plan: find the delegate, replace it with the very last item in the array, then delete the last item
      for(uint i=0; i<length; i++) {
        if(burnDelegates[i]==_burnDelegate) {
          burnDelegates[i] = lastDelegate;
          delete burnDelegates[length-1];
          burnDelegates.length--;
          break;
        }
      }
    }

    RevokeBurnDelegate(_burnDelegate);
    return true;
  }