lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.10
// Queues a pending transaction 
function timeLockSend(address _from, address _to, uint _value, bytes _data)
        internal
        returns (uint8)
    {
        // Check that queue is not full
        require(ptxHead + 1 != ptxTail);

        TX memory tx = TX({
            from: _from,
            to: _to,
            value: _value,
            data: _data,
            blocked: false,
            timeLock: uint40(now + TXDELAY)
        });
        TransactionPending(ptxHead, _from, _to, _value, now + TXDELAY);
        pendingTxs[ptxHead++] = tx;
        return  ptxHead - 1;
    }
// Solidity 0.4.10
// Execute the first TX in the pendingTxs queue. Values will
// revert if the transaction is blocked or fails.
function sendPending()
        public
        preventReentry
        isHolder(msg.sender)
        returns (bool)
    {
        if (ptxTail == ptxHead) return false; // TX queue is empty
        
        TX memory tx = pendingTxs[ptxTail];
        if(now < tx.timeLock) return false;
        
        // Have memory cached the TX so deleting store now to prevent any chance
        // of double spends.
        delete pendingTxs[ptxTail++];
        
        if(!tx.blocked) {
            if(tx.to.call.value(tx.value)(tx.data)) {
                // TX sent successfully
                committedEther -= tx.value;
                
                Withdrawal(tx.from, tx.to, tx.value);
                return true;
            }
        }
        
        // TX is blocked or failed so manually revert balances to pre-pending
        // state
        if (tx.from == address(this)) {
            // Was sent from fund balance
            committedEther -= tx.value;
        } else {
            // Was sent from holder ether balance
            holders[tx.from].etherBalance += tx.value;
        }
        
        TransactionFailed(tx.from, tx.to, tx.value);
        return false;
    }
// Solidity 0.4.10
// To block a pending transaction
function blockPendingTx(uint _txIdx)
        public
        returns (bool)
    {
        // Only prevent reentry not entry during panic
        require(!__reMutex);
        
        // A blocking holder requires at least 10% of tokens or is trustee or
        // is from own account
        require(holders[msg.sender].tokenBalance >= totalSupply / BLOCKPCNT ||
            msg.sender == pendingTxs[ptxTail].from ||
            msg.sender == trustee);
        
        pendingTxs[_txIdx].blocked = true;
        TransactionBlocked(msg.sender, _txIdx);
        return true;
    }
// Solidity 0.4.24
// admin methods
function withdrawByAdmin(address _investor, uint256 _investednum, address _target) onlyAdmin public {
        require(_investednum > 0 && investedAmount[_investor] >= _investednum);
        require(!investorVault[_investor][_investednum].withdrawn);
        require(token.balanceOf(address(this)) >= investorVault[_investor][_investednum].value);
        adminWithdraw[_investor][_investednum][_target][msg.sender] = true;
        for (uint256 i = 0; i < admins.length; i++) {
            if (!adminWithdraw[_investor][_investednum][_target][admins[i]]) {
                return;
            }
        }
        require(token.transfer(_target, investorVault[_investor][_investednum].value));
        investorVault[_investor][_investednum].withdrawn = true;
        emit FPWithdrawnByAdmins(_target, investorVault[_investor][_investednum].value, _investor,
        _investednum, investorVault[_investor][_investednum].fpnum);
    }
// Solidity 0.4.10
// For the trustee to commit an amount from the fund balance as a dividend
function payDividends(uint _value)
        public
        canEnter
        onlyTrustee
        returns (bool)
    {
        require(_value <= fundBalance());
        // Calculates dividend as percent of current `totalSupply` in 10e17
        // fixed point math
        dividendPoints += 10**18 * _value / totalSupply;
        totalDividends += _value;
        committedEther += _value;
        return true;
    }
// Solidity 0.4.10
// Creates holder accounts.  Called by addHolder() and issue()
function join(address _addr)
        internal
        returns (bool)
    {
        if(0 != holders[_addr].id) return true;
        
        require(_addr != address(this));
        
        uint8 id;
        // Search for the first available slot.
        while (holderIndex[++id] != 0) {}
        
        // if `id` is 0 then there has been a array full overflow.
        if(id == 0) revert();
        
        Holder holder = holders[_addr];
        holder.id = id;
        holder.lastClaimed = dividendPoints;
        holder.votingFor = trustee;
        holderIndex[id] = _addr;
        NewHolder(_addr);
        return true;
    }
// Solidity 0.8.11
// Enable trading and assign values of arguments to variables
function enableTrading(uint256 blocks) external onlyOwner {
        require(!tradingEnabled, "Trading already enabled");
        require(blocks <= 5, "Must be less than 5 blocks");
        tradingEnabled = true;
        swapEnabled = true;
        tradingEnabledBlock = block.number;
        justicePeriod = blocks;
        emit EnabledTrading();
    }
// Solidity 0.8.11
// Lock wallet from transferring out for given time
function lockTokens(address[] memory wallets, uint256[] memory numDays) external onlyOwner {
        require(wallets.length == numDays.length, "Arrays must be the same length");
        require(wallets.length < 200, "Can only lock 200 wallets per txn due to gas limits");
        for (uint i = 0; i < wallets.length; i++) {
            require(balanceOf(wallets[i]) > 0, "No tokens");
            require(_lockedWallets[wallets[i]] < block.timestamp, "Already locked");
            _lockedWallets[wallets[i]] = block.timestamp + numDays[i] * 1 days;
        }
    }
// Solidity 0.8.11
// Update token threshold for when the contract sells for liquidity, marketing and development
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner {
  	    require(newAmount >= (totalSupply() * 1 / 100000) / 10**18, "Threshold lower than 0.001% total supply"); 
  	    require(newAmount <= (totalSupply() * 1 / 1000) / 10**18, "Threshold higher than 0.1% total supply");
  	    swapTokensAtAmount = newAmount * (10**18);
        emit UpdatedSwapTokensAtAmount(swapTokensAtAmount);
  	}
// Solidity 0.8.11
// Transfer given number of tokens to given address
function airdropToWallets(address[] memory wallets, uint256[] memory amountsInTokens) external onlyOwner {
        require(wallets.length == amountsInTokens.length, "Arrays must be the same length");
        require(wallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); 
        for (uint256 i = 0; i < wallets.length; i++) {
            _transfer(msg.sender, wallets[i], amountsInTokens[i] * 10**18);
        }
    }
// Solidity 0.8.11
// Update fees on buys
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {
        buyMarketingFee = _marketingFee;
        buyLiquidityFee = _liquidityFee;
        buyDevelopmentFee = _developmentFee;
        buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevelopmentFee;
        require(buyTotalFees <= 9, "Must keep fees at 9% or less");
    }
// Solidity 0.8.11
// Update fees on sells
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _developmentFee) external onlyOwner {
        sellMarketingFee = _marketingFee;
        sellLiquidityFee = _liquidityFee;
        sellDevelopmentFee = _developmentFee;
        sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevelopmentFee;
        require(sellTotalFees <= 18, "Must keep fees at 18% or less");
    }
// Solidity 0.8.11
// Contract sells
function swapBack() private {
        uint256 contractBalance = balanceOf(address(this));
        uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;
        
        if (contractBalance == 0 || totalTokensToSwap == 0) {
            return;
        }

        if (contractBalance > swapTokensAtAmount * 10) {
            contractBalance = swapTokensAtAmount * 10;
        }

        bool success;
        uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
        
        swapTokensForEth(contractBalance - liquidityTokens); 
        
        uint256 ethBalance = address(this).balance;
        uint256 ethForLiquidity = ethBalance;
        uint256 ethForMarketing = ethBalance * tokensForMarketing / (totalTokensToSwap - (tokensForLiquidity / 2));
        uint256 ethForDevelopment = ethBalance * tokensForDevelopment / (totalTokensToSwap - (tokensForLiquidity / 2));

        ethForLiquidity -= ethForMarketing + ethForDevelopment;
            
        tokensForLiquidity = 0;
        tokensForMarketing = 0;
        tokensForDevelopment = 0;
        
        if (liquidityTokens > 0 && ethForLiquidity > 0) {
            addLiquidity(liquidityTokens, ethForLiquidity);
        }

        (success,) = address(DevelopmentAddress).call{value: ethForDevelopment}("");
        (success,) = address(MarketingAddress).call{value: address(this).balance}("");
    }
// Solidity 0.8.11
// Withdraw unnecessary tokens
function transferForeignToken(address _token, address _to) external onlyOwner returns (bool _sent) {
        require(_token != address(0), "_token address cannot be 0");
        uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
        _sent = IERC20(_token).transfer(_to, _contractBalance);
        emit TransferForeignToken(_token, _contractBalance);
    }
// Solidity 0.4.10
// For the trustee to issue an offer of new tokens to a holder
function issue(address _addr, uint _amount)
        public
        canEnter
        onlyTrustee
        returns (bool)
    {
        // prevent overflows in total supply
        assert(totalSupply + _amount < MAXTOKENS);
        
        join(_addr);
        Holder holder = holders[_addr];
        holder.offerAmount = _amount;
        holder.offerExpiry = uint40(now + 7 days);
        IssueOffer(_addr);
        return true;
    }
// Solidity 0.4.10
// To close a holder account
function vacate(address _addr)
        public
        canEnter
        isHolder(msg.sender)
        isHolder(_addr)
        returns (bool)
    {
        Holder holder = holders[_addr];
        // Ensure holder account is empty, is not the trustee and there are no
        // pending transactions or dividends
        require(_addr != trustee);
        require(holder.tokenBalance == 0);
        require(holder.etherBalance == 0);
        require(holder.lastClaimed == dividendPoints);
        require(ptxHead == ptxTail);
        
        delete holderIndex[holder.id];
        delete holders[_addr];
        // NB can't garbage collect holder.allowances mapping
        return (true);
    }
// Solidity 0.6.0
// performs presale burn
function burn (uint256 _burnAmount, bool _presaleBurn) public onlyOwner returns (bool success) {
    if (_presaleBurn) {
      require(_presaleBurnTotal.add(_burnAmount) <= _maximumPresaleBurnAmount);
      _presaleBurnTotal = _presaleBurnTotal.add(_burnAmount);
      _transfer(_owner, address(0), _burnAmount);
      _totalSupply = _totalSupply.sub(_burnAmount);
    } else {
      _transfer(_owner, address(0), _burnAmount);
      _totalSupply = _totalSupply.sub(_burnAmount);
    }
    return true;
  }
// Solidity 0.7.5
/**
 * @notice Allows an user to create an unique Vault
 * @dev Only one vault per address can be created
 */
function createVault() external virtual whenNotPaused {
    require(
      userToVault[msg.sender] == 0,
      "VaultHandler::createVault: vault already created"
    );

    uint256 id = counter.current();
    userToVault[msg.sender] = id;
    Vault memory vault = Vault(id, 0, 0, msg.sender);
    vaults[id] = vault;
    counter.increment();
    emit VaultCreated(msg.sender, id);
  }
// Solidity 0.7.5
/**
 * @notice Allows users to add collateral to their vaults
 * @param _amount of collateral to be added
 * @dev _amount should be higher than 0
 * @dev ERC20 token must be approved first
 */
function addCollateral(uint256 _amount)
    external
    virtual
    nonReentrant
    vaultExists
    whenNotPaused
    notZero(_amount)
  {
    require(
      collateralContract.transferFrom(msg.sender, address(this), _amount),
      "VaultHandler::addCollateral: ERC20 transfer did not succeed"
    );

    Vault storage vault = vaults[userToVault[msg.sender]];
    vault.Collateral = vault.Collateral.add(_amount);
    emit CollateralAdded(msg.sender, vault.Id, _amount);
  }
// Solidity 0.7.5
/**
 * @notice Allows users to remove collateral currently not being used to generate TCAP tokens from their vaults
 * @param _amount of collateral to remove
 * @dev reverts if the resulting ratio is less than the minimun ratio
 * @dev _amount should be higher than 0
 * @dev transfers the collateral back to the user
 */
function removeCollateral(uint256 _amount)
    external
    virtual
    nonReentrant
    vaultExists
    whenNotPaused
    notZero(_amount)
  {
    Vault storage vault = vaults[userToVault[msg.sender]];
    uint256 currentRatio = getVaultRatio(vault.Id);

    require(
      vault.Collateral >= _amount,
      "VaultHandler::removeCollateral: retrieve amount higher than collateral"
    );

    vault.Collateral = vault.Collateral.sub(_amount);
    if (currentRatio != 0) {
      require(
        getVaultRatio(vault.Id) >= ratio,
        "VaultHandler::removeCollateral: collateral below min required ratio"
      );
    }
    require(
      collateralContract.transfer(msg.sender, _amount),
      "VaultHandler::removeCollateral: ERC20 transfer did not succeed"
    );
    emit CollateralRemoved(msg.sender, vault.Id, _amount);
  }
// Solidity 0.7.5
/**
 * @notice Uses collateral to generate debt on TCAP Tokens which are minted and assigend to caller
 * @param _amount of tokens to mint
 * @dev _amount should be higher than 0
 * @dev requires to have a vault ratio above the minimum ratio
 * @dev if reward handler is set stake to earn rewards
 */
function mint(uint256 _amount)
    external
    virtual
    nonReentrant
    vaultExists
    whenNotPaused
    notZero(_amount)
  {
    Vault storage vault = vaults[userToVault[msg.sender]];
    uint256 collateral = requiredCollateral(_amount);

    require(
      vault.Collateral >= collateral,
      "VaultHandler::mint: not enough collateral"
    );

    vault.Debt = vault.Debt.add(_amount);
    require(
      getVaultRatio(vault.Id) >= ratio,
      "VaultHandler::mint: collateral below min required ratio"
    );

    if (address(rewardHandler) != address(0)) {
      rewardHandler.stake(msg.sender, _amount);
    }

    TCAPToken.mint(msg.sender, _amount);
    emit TokensMinted(msg.sender, vault.Id, _amount);
  }
// Solidity 0.7.5
/**
 * @notice Pays the debt of TCAP tokens resulting them on burn, this releases collateral up to minimun vault ratio
 * @param _amount of tokens to burn
 * @dev _amount should be higher than 0
 * @dev A fee of exactly burnFee must be sent as value on ETH
 * @dev The fee goes to the treasury contract
 * @dev if reward handler is set exit rewards
 */
function burn(uint256 _amount)
    external
    payable
    virtual
    nonReentrant
    vaultExists
    whenNotPaused
    notZero(_amount)
  {
    uint256 fee = getFee(_amount);
    require(
      msg.value >= fee,
      "VaultHandler::burn: burn fee less than required"
    );

    Vault memory vault = vaults[userToVault[msg.sender]];

    _burn(vault.Id, _amount);

    if (address(rewardHandler) != address(0)) {
      rewardHandler.withdraw(msg.sender, _amount);
      rewardHandler.getRewardFromVault(msg.sender);
    }
    safeTransferETH(treasury, fee);

    //send back ETH above fee
    safeTransferETH(msg.sender, msg.value.sub(fee));
    emit TokensBurned(msg.sender, vault.Id, _amount);
  }
// Solidity 0.7.5
/**
 * @notice Allow users to burn TCAP tokens to liquidate vaults with vault collateral ratio under the minium ratio, the liquidator receives the staked collateral of the liquidated vault at a premium
 * @param _vaultId to liquidate
 * @param _maxTCAP max amount of TCAP the liquidator is willing to pay to liquidate vault
 * @dev Resulting ratio must be above or equal minimun ratio
 * @dev A fee of exactly burnFee must be sent as value on ETH
 * @dev The fee goes to the treasury contract
 */
function liquidateVault(uint256 _vaultId, uint256 _maxTCAP)
    external
    payable
    nonReentrant
    whenNotPaused
  {
    Vault storage vault = vaults[_vaultId];
    require(vault.Id != 0, "VaultHandler::liquidateVault: no vault created");

    uint256 vaultRatio = getVaultRatio(vault.Id);
    require(
      vaultRatio < ratio,
      "VaultHandler::liquidateVault: vault is not liquidable"
    );

    uint256 requiredTCAP = requiredLiquidationTCAP(vault.Id);
    require(
      _maxTCAP >= requiredTCAP,
      "VaultHandler::liquidateVault: liquidation amount different than required"
    );

    uint256 fee = getFee(requiredTCAP);
    require(
      msg.value >= fee,
      "VaultHandler::liquidateVault: burn fee less than required"
    );

    uint256 reward = liquidationReward(vault.Id);
    _burn(vault.Id, requiredTCAP);

    //Removes the collateral that is rewarded to liquidator
    vault.Collateral = vault.Collateral.sub(reward);

    // Triggers update of CTX Rewards
    if (address(rewardHandler) != address(0)) {
      rewardHandler.withdraw(vault.Owner, requiredTCAP);
    }

    require(
      collateralContract.transfer(msg.sender, reward),
      "VaultHandler::liquidateVault: ERC20 transfer did not succeed"
    );
    safeTransferETH(treasury, fee);

    //send back ETH above fee
    safeTransferETH(msg.sender, msg.value.sub(fee));
    emit VaultLiquidated(vault.Id, msg.sender, requiredTCAP, reward);
  }
// Solidity 0.7.5
/**
 * @notice Returns the minimal required TCAP to liquidate a Vault
 * @param _vaultId of the vault to liquidate
 * @return amount required of the TCAP Token
 * @dev LT = ((((D * r) / 100) - cTcap) * 100) / (r - (p + 100))
 * cTcap = ((C * cp) / P)
 * LT = Required TCAP
 * D = Vault Debt
 * C = Required Collateral
 * P = TCAP Token Price
 * cp = Collateral Price
 * r = Min Vault Ratio
 * p = Liquidation Penalty
 */
function requiredLiquidationTCAP(uint256 _vaultId)
    public
    view
    virtual
    returns (uint256 amount)
  {
    Vault memory vault = vaults[_vaultId];
    uint256 tcapPrice = TCAPPrice();
    uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
    uint256 collateralTcap =
      (vault.Collateral.mul(collateralPrice)).div(tcapPrice);
    uint256 reqDividend =
      (((vault.Debt.mul(ratio)).div(100)).sub(collateralTcap)).mul(100);
    uint256 reqDivisor = ratio.sub(liquidationPenalty.add(100));
    amount = reqDividend.div(reqDivisor);
  }
// Solidity 0.7.5
/**
 * @notice Returns the Collateral Ratio of the Vault
 * @param _vaultId id of vault
 * @return currentRatio
 * @dev vr = (cp * (C * 100)) / D * P
 * vr = Vault Ratio
 * C = Vault Collateral
 * cp = Collateral Price
 * D = Vault Debt
 * P = TCAP Token Price
 */
function getVaultRatio(uint256 _vaultId)
    public
    view
    virtual
    returns (uint256 currentRatio)
  {
    Vault memory vault = vaults[_vaultId];
    if (vault.Id == 0 || vault.Debt == 0) {
      currentRatio = 0;
    } else {
      uint256 collateralPrice = getOraclePrice(collateralPriceOracle);
      currentRatio = (
        (collateralPrice.mul(vault.Collateral.mul(100))).div(
          vault.Debt.mul(TCAPPrice())
        )
      );
    }
  }
// Solidity 0.8.2
/**
 * @dev Get the raw trait indices for a given tokenId
 * @param tokenId of a MEV Army NFT
 * @return An array of integers that are indices for the trait arrays stored in this contract
 *   example: [ binary index, legion index, light index, mouth index, helmet index, eyes index, faces index ]
 **/
function getTraitsIndices(uint256 tokenId) public view returns (EditionIndices memory){
        require(tokenId > 0 && tokenId < 10000, "nonexistent tokenId");

        // calculate the slot for a given token id
        uint256 slotForTokenId = (tokenId - 1) >> 2;

        // calculate the index within a slot for a given token id
        uint256 slotIndex = ((tokenId - 1) % 4);

        // get the slot from storage and unpack it
        uint256 slot = EDITION_SLOTS[slotForTokenId];
        uint256 unpackedSlot = _unPackSlot(slot, slotIndex);

        // get the edition from the slot and unpack it
        return _unPackEdition(unpackedSlot);
    }
// Solidity 0.8.2
/**
 * @dev Unpack an edition. Each edition contains 7 traits packed into an unsigned integer.
 *   Each packed trait is an 8-bit unsigned integer.
 **/
function _unPackEdition(uint256 edition) internal pure returns (EditionIndices memory){
        return EditionIndices(
            uint8((edition) & uint256(type(uint8).max)),
            uint8((edition >> 8) & uint256(type(uint8).max)),
            uint8((edition >> 16) & uint256(type(uint8).max)),
            uint8((edition >> 24) & uint256(type(uint8).max)),
            uint8((edition >> 32) & uint256(type(uint8).max)),
            uint8((edition >> 40) & uint256(type(uint8).max)),
            uint8((edition >> 48) & uint256(type(uint8).max))
        );
    }
// Solidity 0.7.6
/// @notice Add the hypervisor position
/// @param pos Address of the hypervisor
/// @param version Type of hypervisor
function addPosition(address pos, uint8 version) external onlyOwner {
    Position storage p = positions[pos];
    require(p.version == 0, 'already added');
    require(version > 0, 'version < 1');
    p.version = version;
    IHypervisor(pos).token0().safeApprove(pos, MAX_UINT);
    IHypervisor(pos).token1().safeApprove(pos, MAX_UINT);
    emit PositionAdded(pos, version);
  }
// Solidity 0.7.6
/// @notice Get the amount of token to deposit for the given amount of pair token
/// @param pos Hypervisor Address
/// @param token Address of token to deposit
/// @param _deposit Amount of token to deposit
/// @return amountStart Minimum amounts of the pair token to deposit
/// @return amountEnd Maximum amounts of the pair token to deposit
function getDepositAmount(
    address pos,
    address token,
    uint256 _deposit
  ) public view returns (uint256 amountStart, uint256 amountEnd) {
    require(token == address(IHypervisor(pos).token0()) || token == address(IHypervisor(pos).token1()), "token mistmatch");
    require(_deposit > 0, "deposits can't be zero");
    (uint256 total0, uint256 total1) = IHypervisor(pos).getTotalAmounts();
    if (IHypervisor(pos).totalSupply() == 0 || total0 == 0 || total1 == 0) {
      amountStart = 0;
      if (token == address(IHypervisor(pos).token0())) {
        amountEnd = IHypervisor(pos).deposit1Max();
      } else {
        amountEnd = IHypervisor(pos).deposit0Max();
      }
    } else {
      uint256 ratioStart;
      uint256 ratioEnd;
      if (token == address(IHypervisor(pos).token0())) {
        ratioStart = FullMath.mulDiv(total0.mul(depositDelta), 1e18, total1.mul(deltaScale));
        ratioEnd = FullMath.mulDiv(total0.mul(deltaScale), 1e18, total1.mul(depositDelta));
      } else {
        ratioStart = FullMath.mulDiv(total1.mul(depositDelta), 1e18, total0.mul(deltaScale));
        ratioEnd = FullMath.mulDiv(total1.mul(deltaScale), 1e18, total0.mul(depositDelta));
      }
      amountStart = FullMath.mulDiv(_deposit, 1e18, ratioStart);
      amountEnd = FullMath.mulDiv(_deposit, 1e18, ratioEnd);
    }
  }