lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.9
//swaps the token on the contract for Marketing ETH and LP Token.
//always swaps the sellLimit of token to avoid a large price impact
function _swapContractToken() private lockTheSwap{
        uint256 contractBalance=_balances[address(this)];
        uint16 totalTax=_liquidityTax+_stakingTax;
        uint256 tokenToSwap = _setSellAmount;
        //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0
        if(contractBalance<tokenToSwap||totalTax==0){
            return;
        }
        //splits the token in TokenForLiquidity and tokenForMarketing
        uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax;
        uint256 tokenForMarketing= tokenToSwap-tokenForLiquidity;

        //splits tokenForLiquidity in 2 halves
        uint256 liqToken=tokenForLiquidity/2;
        uint256 liqETHToken=tokenForLiquidity-liqToken;

        //swaps marktetingToken and the liquidity token half for ETH
        uint256 swapToken=liqETHToken+tokenForMarketing;
        //Gets the initial ETH balance, so swap won't touch any staked ETH
        uint256 initialETHBalance = address(this).balance;
        _swapTokenForETH(swapToken);
        uint256 newETH=(address(this).balance - initialETHBalance);
        //calculates the amount of ETH belonging to the LP-Pair and converts them to LP
        uint256 liqETH = (newETH*liqETHToken)/swapToken;
        _addLiquidity(liqToken, liqETH);
        //Get the ETH balance after LP generation to get the
        //exact amount of token left for Staking
        uint256 distributeETH=(address(this).balance - initialETHBalance);
        //distributes remaining ETH between stakers and Marketing
        _distributeStake(distributeETH);
    }
// Solidity 0.8.9
//Limits need to be at least target, to avoid setting value to 0(avoid potential Honeypot)
function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyOwner{
        //SellLimit needs to be below 1% to avoid a Large Price impact when generating auto LP
        require(newSellLimit<_circulatingSupply/100);
        //Adds decimals to limits
        newBalanceLimit=newBalanceLimit*10**_decimals;
        newSellLimit=newSellLimit*10**_decimals;
        //Calculates the target Limits based on supply
        uint256 targetBalanceLimit=_circulatingSupply/BalanceLimitDivider;
        uint256 targetSellLimit=_circulatingSupply/SellLimitDivider;

        require((newBalanceLimit>=targetBalanceLimit), 
        "newBalanceLimit needs to be at least target");
        require((newSellLimit>=targetSellLimit), 
        "newSellLimit needs to be at least target");

        balanceLimit = newBalanceLimit;
        sellLimit = newSellLimit;     
    }
// Solidity 0.8.9
//Release Liquidity Tokens once unlock time is over
function TeamReleaseLiquidity() public onlyOwner {
        //Only callable if liquidity Unlock time is over
        require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
        
        IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress);
        uint256 amount = liquidityToken.balanceOf(address(this));

        //Liquidity release if something goes wrong at start
        liquidityToken.transfer(TeamWallet, amount);
        
    }
// Solidity 0.8.9
//Removes Liquidity once unlock Time is over, 
function TeamRemoveLiquidity(bool addToStaking) public onlyOwner{
        //Only callable if liquidity Unlock time is over
        require(block.timestamp >= _liquidityUnlockTime, "Not yet unlocked");
        _liquidityUnlockTime=block.timestamp+DefaultLiquidityLockTime;
        IuniswapV2ERC20 liquidityToken = IuniswapV2ERC20(_liquidityTokenAddress);
        uint256 amount = liquidityToken.balanceOf(address(this));

        liquidityToken.approve(address(_uniswapV2Router),amount);
        //Removes Liquidity and either distributes liquidity ETH to stakers, or 
        // adds them to marketing Balance
        //Token will be converted
        //to Liquidity and Staking ETH again
        uint256 initialETHBalance = address(this).balance;
        _uniswapV2Router.removeLiquidityETHSupportingFeeOnTransferTokens(
            address(this),
            amount,
            0,
            0,
            address(this),
            block.timestamp
            );
        uint256 newETHBalance = address(this).balance-initialETHBalance;
        if(addToStaking){
            _distributeStake(newETHBalance);
        }
        else{
            marketingBalance+=newETHBalance;
        }

    }
// Solidity 0.5.12
// main function which will make the investments
function LetsInvest() public payable returns(uint) {
        require (msg.value > 100000000000000);
        require (msg.sender != address(0));
        uint invest_amt = msg.value;
        address payable investor = address(msg.sender);
        uint sBTCPortion = SafeMath.div(SafeMath.mul(invest_amt,sBTCPercentage),100);
        uint sETHPortion = SafeMath.sub(invest_amt, sBTCPortion);
        require (SafeMath.sub(invest_amt, SafeMath.add(sBTCPortion, sETHPortion)) ==0 );
        Invest2_sBTCContract.LetsInvestin_sBTC.value(sBTCPortion)(investor);
        Invest2_sETHContract.LetsInvestin_sETH.value(sETHPortion)(investor);
    }
// Solidity 0.6.8
// Converts ETH to Tokens and sends new Tokens to the sender
receive () external payable {
    require(startDate > 0 && now.sub(startDate) <= 5 days);
    require(Token.balanceOf(address(this)) > 0);
    require(msg.value >= 0.1 ether && msg.value <= 60 ether);
    require(!presaleClosed);
     
    if (now.sub(startDate) <= 1 days) {
       amount = msg.value.mul(20);
    } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) {
       amount = msg.value.mul(35).div(2);
    } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) {
       amount = msg.value.mul(15);
    } else if(now.sub(startDate) > 3 days) {
       amount = msg.value.mul(25).div(2);
    }
    
    require(amount <= Token.balanceOf(address(this)));
    // update constants.
    totalSold = totalSold.add(amount);
    collectedETH = collectedETH.add(msg.value);
    // transfer the tokens.
    Token.transfer(msg.sender, amount);
  }
// Solidity 0.6.8
// Converts ETH to Tokens 1and sends new Tokens to the sender
function contribute() external payable {
    require(startDate > 0 && now.sub(startDate) <= 5 days);
    require(Token.balanceOf(address(this)) > 0);
    require(msg.value >= 0.1 ether && msg.value <= 60 ether);
    require(!presaleClosed);
     
    if (now.sub(startDate) <= 1 days) {
       amount = msg.value.mul(20);
    } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) {
       amount = msg.value.mul(35).div(2);
    } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) {
       amount = msg.value.mul(15);
    } else if(now.sub(startDate) > 3 days) {
       amount = msg.value.mul(25).div(2);
    }
    
    require(amount <= Token.balanceOf(address(this)));
    // update constants.
    totalSold = totalSold.add(amount);
    collectedETH = collectedETH.add(msg.value);
    // transfer the tokens.
    Token.transfer(msg.sender, amount);
  }
// Solidity 0.4.25
//event LogBool(uint8 id, bool value);
//event LogAddress(uint8 id, address value);
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_, address DmexOracleContract_, address poolAddress) {
        owner               = msg.sender;
        feeAccount          = feeAccount_;
        makerFee            = makerFee_;
        takerFee            = takerFee_;

        exchangeContract    = exchangeContract_;
        DmexOracleContract    = DmexOracleContract_;

        pools[poolAddress] = true;
    }
// Solidity 0.6.12
// public methods
// public method to harvest all the unharvested epochs until current epoch - 1
function massHarvest() external returns (uint){
        uint totalDistributedValue;
        uint epochId = _getEpochId().sub(1); // fails in epoch 0
        // force max number of epochs
        if (epochId > NR_OF_EPOCHS) {
            epochId = NR_OF_EPOCHS;
        }

        for (uint128 i = lastEpochIdHarvested[msg.sender] + 1; i <= epochId; i++) {
            // i = epochId
            // compute distributed Value and do one single transfer at the end
            totalDistributedValue += _harvest(i);
        }

        emit MassHarvest(msg.sender, epochId - lastEpochIdHarvested[msg.sender], totalDistributedValue);

        if (totalDistributedValue > 0) {
            _xfund.transferFrom(_communityVault, msg.sender, totalDistributedValue);
        }

        return totalDistributedValue;
    }
// Solidity 0.6.12
// internal methods
function _initEpoch(uint128 epochId) internal {
        require(lastInitializedEpoch.add(1) == epochId, "Epoch can be init only in order");
        lastInitializedEpoch = epochId;
        // call the staking smart contract to init the epoch
        epochs[epochId] = _getPoolSize(epochId);
    }
// Solidity 0.6.12
/*
 @notice This claims your deevy bag in L2.
 */
function warpLoot(
        uint256 lootId,
        uint256 maxSubmissionCost,
        uint256 maxGas,
        uint256 gasPriceBid
    ) external payable returns (uint256) {
        require(msg.value > 0, "MSG_VALUE_IS_REQUIRED");
        require(
            loot.ownerOf(lootId) == msg.sender,
            "SENDER_ISNT_LOOT_ID_OWNER"
        );

        bytes memory data =
            abi.encodeWithSelector(
                IDeevyBridgeMinter.warpBag.selector,
                msg.sender,
                lootId
            );

        uint256 ticketID =
            inbox.createRetryableTicket{value: msg.value}(
                l2Target,
                0,
                maxSubmissionCost,
                msg.sender,
                msg.sender,
                maxGas,
                gasPriceBid,
                data
            );

        lootsToTickets[lootId] = ticketID;
        emit RetryableTicketCreated(ticketID);
        return ticketID;
    }
// Solidity 0.4.24
// String helpers below were taken from Oraclize.
// https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol
function strConcat(string _a, string _b) internal pure returns (string) {
    bytes memory _ba = bytes(_a);
    bytes memory _bb = bytes(_b);
    string memory ab = new string(_ba.length + _bb.length);
    bytes memory bab = bytes(ab);
    uint k = 0;
    for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
    for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
    return string(bab);
  }
// Solidity 0.8.7
// Called initially to bootstrap the game
function bootstrap(
    uint _bootstrapWinnings
  )
  public
  onlyOwner
  returns (bool) {
    require(!isBootstrapped, "Game already bootstrapped");
    bootstrapWinnings = _bootstrapWinnings;
    revenue += _bootstrapWinnings;
    isBootstrapped = true;
    startTime = block.timestamp;
    weth.safeTransferFrom(msg.sender, address(this), _bootstrapWinnings);
    return true;
  }
// Solidity 0.8.7
// Process random words from chainlink VRF2
function fulfillRandomWords(
    uint256 requestId, /* requestId */
    uint256[] memory randomWords
  ) internal override {
    for (uint i = 0; i < randomWords.length; i++) {
      diceRolls[++rollCount].roll = getFormattedNumber(randomWords[i]);
      diceRolls[rollCount].roller = rollRequests[requestId];

      // If the game was over between rolls - don't perform any of the below logic
      if (!isGameOver()) {
        if (diceRolls[rollCount].roll == winningNumber) {
          // User wins
          winner = diceRolls[rollCount];
          // Transfer revenue to winner
          collectFees();
          uint revenueSplit = getRevenueSplit();
          uint winnings = revenue - feesCollected - revenueSplit;
          weth.safeTransfer(winner.roller, winnings);
          emit LogGameOver(winner.roller, winnings);
        } else if (diceRolls[rollCount].roll >= revenueSplitRollThreshold) {
          totalRevenueSplitShares += 1;
          revenueSplitSharesPerUser[diceRolls[rollCount].roller] += 1;
        }

        if (diceRolls[rollCount].roll != winningNumber) {
          int diff = getDiff(diceRolls[rollCount].roll, winningNumber);
          int currentWinnerDiff = getDiff(currentWinner.roll, winningNumber);

          if (diff <= currentWinnerDiff)  {
            currentWinner = diceRolls[rollCount];
            emit LogNewCurrentWinner(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller);
          }
        }
      } else
        emit LogDiscardedRollResult(requestId, rollCount, diceRolls[rollCount].roller);

      emit LogOnRollResult(requestId, rollCount, diceRolls[rollCount].roll, diceRolls[rollCount].roller);
    }
  }
// Solidity 0.8.7
// Ends a game that is past it's duration without a winner
function endGame()
  public
  returns (bool) {
    require(
      hasGameDurationElapsed() && winner.roller == address(0), 
      "Game duration hasn't elapsed without a winner"
    );
    winner = currentWinner;
    // Transfer revenue to winner
    collectFees();
    uint revenueSplit = getRevenueSplit();
    uint winnings = revenue - feesCollected - revenueSplit;
    weth.safeTransfer(winner.roller, winnings);
    emit LogGameOver(winner.roller, winnings);
    return true;
  }
// Solidity 0.8.7
// Allows users to collect their share of revenue split after a game is over  
function collectRevenueSplit() external {
    require(isGameOver(), "Game isn't over");
    require(revenueSplitSharesPerUser[msg.sender] > 0, "User does not have any revenue split shares");
    require(revenueSplitCollectedPerUser[msg.sender] == 0, "User has already collected revenue split");
    uint revenueSplit = getRevenueSplit();
    uint userRevenueSplit = revenueSplit * revenueSplitSharesPerUser[msg.sender] / totalRevenueSplitShares; 
    revenueSplitCollectedPerUser[msg.sender] = userRevenueSplit;
    weth.safeTransfer(msg.sender, userRevenueSplit);
    emit LogOnCollectRevenueSplit(msg.sender, userRevenueSplit);
  }
// Solidity 0.8.7
// Roll dice once
function rollDice() external {
    require(isSingleRollEnabled, "Single rolls are not currently enabled");
    require(isBootstrapped, "Game is not bootstrapped");
    require(!isGameOver(), "Game is over");
    revenue += ticketSize;
    weth.safeTransferFrom(msg.sender, address(this), ticketSize);
    
    // Will revert if subscription is not set and funded.
    uint requestId = COORDINATOR.requestRandomWords(
      keyHash,
      s_subscriptionId,
      requestConfirmations,
      callbackGasLimit,
      1
    );
    rollRequests[requestId] = msg.sender;

    emit LogNewRollRequest(requestId, msg.sender);
  }
// Solidity 0.8.7
// Approve WETH once and roll multiple times
function rollMultipleDice(uint32 times) external {
    require(isBootstrapped, "Game is not bootstrapped");
    require(!isGameOver(), "Game is over");
    require(times > 1 && times <= 5, "Should be >=1 and <=5 rolls in 1 txn");
    uint total = ticketSize * times;
    revenue += total;
    weth.safeTransferFrom(msg.sender, address(this), total);
    
    // Will revert if subscription is not set and funded.
    uint requestId = COORDINATOR.requestRandomWords(
      keyHash,
      s_subscriptionId,
      requestConfirmations,
      callbackGasLimit,
      times
    );
    rollRequests[requestId] = msg.sender;
    emit LogNewRollRequest(requestId, msg.sender);
  }
// Solidity 0.5.1
/**
 * @dev setAccessLevel for a user restricted to contract owner
 * @dev Ideally, check for whole number should be implemented (TODO)
 * @param _user address that access level is to be set for
 * @param _access uint256 level of access to give 0, 1, 2, 3.
 */
function setAccessLevel(
        address _user,
        uint256 _access
    )
        public
        adminAccessLevelOnly
    {
        require(
            accessLevel[_user] < 4,
            "Cannot setAccessLevel for Admin Level Access User"
        ); /// owner access not allowed to be set

        if (_access < 0 || _access > 4) {
            revert("erroneous access level");
        } else {
            accessLevel[_user] = _access;
        }

        emit AccessLevelSet(_user, _access, msg.sender);
    }
// Solidity 0.4.24
/// @dev External function to add a checklist item to our mystery set.
///   Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8).
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner {
    require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first.");
    require(unreleasedCount() < 56, "You can't add any more checklist items.");
    require(_playerId < playerCount, "This player doesn't exist in our player list.");
    unreleasedChecklistItems.push(ChecklistItem({
      playerId: _playerId,
      tier: _tier
    }));
  }
// Solidity 0.4.24
/// @dev Returns the mint limit for a given checklist item, based on its tier.
/// @param _checklistId Which checklist item we need to get the limit for.
/// @return How much of this checklist item we are allowed to mint.
function limitForChecklistId(uint8 _checklistId) external view returns (uint16) {
    RarityTier rarityTier;
    uint8 index;
    if (_checklistId < 100) { // Originals = #000 to #099
      rarityTier = originalChecklistItems[_checklistId].tier;
    } else if (_checklistId < 200) { // Iconics = #100 to #131
      index = _checklistId - 100;
      require(index < iconicsCount(), "This Iconics checklist item doesn't exist.");
      rarityTier = iconicChecklistItems[index].tier;
    } else { // Unreleased = #200 to max #255
      index = _checklistId - 200;
      require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist.");
      rarityTier = unreleasedChecklistItems[index].tier;
    }
    return tierLimits[uint8(rarityTier)];
  }
// Solidity 0.4.24
/// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned
///   by this address. The second returns the corresponding checklist ID for each of these cards.
///   There are a few places we need this info in the web app and short of being able to return an
///   actual array of Cards, this is the best solution we could come up with...
function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) {
    uint256[] memory cardIds = ownedTokens[_owner];
    uint256 cardCount = cardIds.length;
    uint8[] memory checklistIds = new uint8[](cardCount);

    for (uint256 i = 0; i < cardCount; i++) {
      uint256 cardId = cardIds[i];
      checklistIds[i] = cards[cardId].checklistId;
    }

    return (cardIds, checklistIds);
  }
// Solidity 0.4.24
/// @dev An internal method that creates a new card and stores it.
///  Emits both a CardMinted and a Transfer event.
/// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol)
/// @param _owner The card's first owner!
function _mintCard(
    uint8 _checklistId,
    address _owner
  )
    internal
    returns (uint256)
  {
    uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId);
    require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!");
    uint16 serialNumber = ++mintedCountForChecklistId[_checklistId];
    Card memory newCard = Card({
      mintTime: uint32(now),
      checklistId: _checklistId,
      serialNumber: serialNumber
    });
    uint256 newCardId = cards.push(newCard) - 1;
    emit CardMinted(newCardId);
    _mint(_owner, newCardId);
    return newCardId;
  }
// Solidity 0.4.24
/// @dev Allows the contract at packSaleAddress to mint cards.
/// @param _checklistId The checklist item represented by this new card.
/// @param _owner The card's first owner!
/// @return The new card's ID.
function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) {
    require(msg.sender == packSaleAddress, "Only the pack sale contract can mint here.");
    require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
    return _mintCard(_checklistId, _owner);
  }
// Solidity 0.4.24
/// @dev Allows the owner to mint cards from our Unreleased Set.
/// @param _checklistId The checklist item represented by this new card. Must be >= 200.
/// @param _owner The card's first owner!
function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner {
    require(_checklistId >= 200, "You can only use this to mint unreleased cards.");
    require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
    _mintCard(_checklistId, _owner);
  }
// Solidity 0.4.24
/// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again.
/// @param _checklistId The Iconic or Unreleased card we want to remove from circulation.
function pullFromCirculation(uint8 _checklistId) external {
    bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress);
    require(ownerOrPackSale, "Only the owner or pack sale can take checklist items out of circulation.");
    require(_checklistId >= 100, "This function is reserved for Iconics and Unreleased sets.");
    outOfCirculation[_checklistId] = true;
    emit PulledFromCirculation(_checklistId);
  }
// Solidity 0.4.24
/// @dev Allows the maker to cancel a trade that hasn't been filled yet.
/// @param _maker Address of the maker (i.e. trade creator).
/// @param _makerCardId ID of the card the maker has agreed to give up.
/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)
/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi").
///                                If not, then it's a card ID (e.g. "Lionel Messi #8/100").
/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
function cancelTrade(
    address _maker,
    uint256 _makerCardId,
    address _taker,
    uint256 _takerCardOrChecklistId,
    uint256 _salt)
    external
  {
    require(_maker == msg.sender, "Only the trade creator can cancel this trade.");

    bytes32 tradeHash = getTradeHash(
      _maker,
      _makerCardId,
      _taker,
      _takerCardOrChecklistId,
      _salt
    );

    require(tradeStates[tradeHash] == TradeState.Valid, "This trade has already been cancelled or filled.");
    tradeStates[tradeHash] = TradeState.Cancelled;
    emit TradeCancelled(tradeHash, _maker);
  }
// Solidity 0.4.24
/// @dev Calculates Keccak-256 hash of a trade with specified parameters.
/// @param _maker Address of the maker (i.e. trade creator).
/// @param _makerCardId ID of the card the maker has agreed to give up.
/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)
/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi").
///                                If not, then it's a card ID (e.g. "Lionel Messi #8/100").
/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
/// @return Keccak-256 hash of trade.
function getTradeHash(
    address _maker,
    uint256 _makerCardId,
    address _taker,
    uint256 _takerCardOrChecklistId,
    uint256 _salt)
    public
    view
    returns (bytes32)
  {
    // Hashing the contract address prevents a trade from being replayed on any new trade contract we deploy.
    bytes memory packed = abi.encodePacked(this, _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt);
    return keccak256(packed);
  }