lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/**
 * @notice Creates a new FarmUniswap contract and registers it in the
 * .sol. All farming rewards are locked in the FarmUniswap Contract
 */
function createFarmUniswap(IERC20 _rewardToken, uint256 _amount, IERC20 _lpToken, IUniFactory _swapFactory, uint256 _blockReward, uint256 _startBlock, uint256 _bonusEndBlock, uint256 _bonus) public onlyOwner returns (address){
    require(_startBlock > block.number, 'START'); // ideally at least 24 hours more to give farmers time
    require(_bonus > 0, 'BONUS');
    require(address(_rewardToken) != address(0), 'REWARD TOKEN');
    require(_blockReward > 1000, 'BLOCK REWARD'); // minimum 1000 divisibility per block reward
    IUniFactory swapFactory = _swapFactory;
    // ensure this pair is on swapFactory by querying the factory
    IUniswapV2Pair lpair = IUniswapV2Pair(address(_lpToken));
    address factoryPairAddress = swapFactory.getPair(lpair.token0(), lpair.token1());
    require(factoryPairAddress == address(_lpToken), 'This pair is not on _swapFactory exchange');

    FarmParameters memory params;
    (params.endBlock, params.requiredAmount) = determineEndBlock(_amount, _blockReward, _startBlock, _bonusEndBlock, _bonus);

    TransferHelper.safeTransferFrom(address(_rewardToken), address(_msgSender()), address(this), params.requiredAmount);
    FarmUniswap newFarm = new FarmUniswap(address(factory), address(this));
    TransferHelper.safeApprove(address(_rewardToken), address(newFarm), params.requiredAmount);
    newFarm.init(_rewardToken, params.requiredAmount, _lpToken, _blockReward, _startBlock, params.endBlock, _bonusEndBlock, _bonus);

    factory.registerFarm(address(newFarm));
    return (address(newFarm));
  }
// Solidity 0.7.6
// This is a final distribution after phase 2 is fihished, everyone who left the
// request with register() method will get remaining ETH amount
// in proportion to their exchanged tokens
function startFinalDistribution(uint256 start_index, uint256 end_index) external onlyOwnerOrAdmin {
        require(end_index < getNumberOfParticipants());
        
        uint256 j = getCurrentPhaseIndex();
        require(j == 3 && !phases[j].IS_FINISHED, "Not Allowed phase");
        // Final Phase

        uint256 pointfix = 1000000000000000000;
        // 10^18

        for (uint i = start_index; i <= end_index; i++) {
            if(!isRegistration(_participants[i]) || isFinalWithdraw(_participants[i])){
                continue;
            }
            
            uint256 piece = getBurntAmountByAddress(_participants[i]).mul(pointfix).div(sum_burnt_amount_registered);
            uint256 value = final_distribution_balance.mul(piece).div(pointfix);
            
            if (value > 0) {
                _is_final_withdraw[_participants[i]] = true;
                (bool success,) = _participants[i].call{value : value}("");
                require(success, "Transfer failed");
                emit LogWithdrawETH(_participants[i], value);
            }
        }

    }
// Solidity 0.7.6
// this method reverts the current phase to the previous one
function revertPhase() external selfCall {
        uint256 i = getCurrentPhaseIndex();

        require(i > 0, "Initialize phase is already active");

        phases[i].IS_STARTED = false;
        phases[i].IS_FINISHED = false;

        phases[i - 1].IS_STARTED = true;
        phases[i - 1].IS_FINISHED = false;
    }
// Solidity 0.4.21
/* Buying */
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
    if (_price < increaseLimit1) {
      return _price.mul(200).div(95);
    } else if (_price < increaseLimit2) {
      return _price.mul(135).div(96);
    } else if (_price < increaseLimit3) {
      return _price.mul(125).div(97);
    } else if (_price < increaseLimit4) {
      return _price.mul(117).div(97);
    } else {
      return _price.mul(115).div(98);
    }
  }
// Solidity 0.4.8
/**
 * Create presale contract where lock up period is given days
 */
function PresaleFundCollector(address _owner, uint _freezeEndsAt, uint _weiMinimumLimit) {

    owner = _owner;

    // Give argument
    if(_freezeEndsAt == 0) {
      throw;
    }

    // Give argument
    if(_weiMinimumLimit == 0) {
      throw;
    }

    weiMinimumLimit = _weiMinimumLimit;
    freezeEndsAt = _freezeEndsAt;
  }
// Solidity 0.4.8
/**
 * Participate to a presale.
 */
function invest() public payable {

    // Cannot invest anymore through crowdsale when moving has begun
    if(moving) throw;

    address investor = msg.sender;

    bool existing = balances[investor] > 0;

    balances[investor] = balances[investor].plus(msg.value);

    // Need to fulfill minimum limit
    if(balances[investor] < weiMinimumLimit) {
      throw;
    }

    // This is a new investor
    if(!existing) {

      // Limit number of investors to prevent too long loops
      if(investorCount >= MAX_INVESTORS) throw;

      investors.push(investor);
      investorCount++;
    }

    Invested(investor, msg.value);
  }
// Solidity 0.4.8
/**
 * Load funds to the crowdsale for all investor.
 *
 */
function parcipateCrowdsaleAll() public {

    // We might hit a max gas limit in this loop,
    // and in this case you can simply call parcipateCrowdsaleInvestor() for all investors
    for(uint i=0; i<investors.length; i++) {
       parcipateCrowdsaleInvestor(investors[i]);
    }
  }
// Solidity 0.4.8
/**
 * ICO never happened. Allow refund.
 */
function refund() {

    // Trying to ask refund too soon
    if(now < freezeEndsAt) throw;

    // We have started to move funds
    moving = true;

    address investor = msg.sender;
    if(balances[investor] == 0) throw;
    uint amount = balances[investor];
    delete balances[investor];
    if(!investor.send(amount)) throw;
    Refunded(investor, amount);
  }
// Solidity 0.6.12
/**
 * @notice initialize the farming contract. This is called only once upon farm creation and the FarmGenerator ensures the farm has the correct paramaters
 */
function init(
        IERC20 _rewardToken,
        uint256 _amount,
        IERC20 _lpToken,
        uint256 _blockReward,
        uint256 _startBlock,
        uint256 _endBlock,
        uint256 _bonusEndBlock,
        uint256 _bonus
    ) public {
        address msgSender = _msgSender();
        require(msgSender == address(farmGenerator), "FORBIDDEN");

        TransferHelper.safeTransferFrom(
            address(_rewardToken),
            msgSender,
            address(this),
            _amount
        );
        farmInfo.rewardToken = _rewardToken;

        farmInfo.startBlock = _startBlock;
        farmInfo.blockReward = _blockReward;
        farmInfo.bonusEndBlock = _bonusEndBlock;
        farmInfo.bonus = _bonus;

        uint256 lastRewardBlock =
            block.number > _startBlock ? block.number : _startBlock;
        farmInfo.lpToken = _lpToken;
        farmInfo.lastRewardBlock = lastRewardBlock;
        farmInfo.accRewardPerShare = 0;

        farmInfo.endBlock = _endBlock;
        farmInfo.farmableSupply = _amount;
    }
// Solidity 0.8.9
/**
 * @dev Mint pool shares for a given stake amount
 * @param _stakeAmount The amount of underlying to stake
 * @return shares The number of pool shares minted
 */
function mint(uint256 _stakeAmount) external returns (uint256 shares) {
    require(
      stakedToken.allowance(msg.sender, address(this)) >= _stakeAmount,
      "mint: insufficient allowance"
    );

    // Grab the pre-deposit balance and shares for comparison
    uint256 oldBalance = stakedToken.balanceOf(address(this));
    uint256 oldShares = totalSupply();

    // Pull user's tokens into the pool
    stakedToken.safeTransferFrom(msg.sender, address(this), _stakeAmount);

    // Calculate the fee for minting
    uint256 fee = (_stakeAmount * mintFee) / 1e18;
    if (fee != 0) {
      stakedToken.safeTransfer(feePayee, fee);
      _stakeAmount -= fee;
      emit Fee(fee);
    }

    // Calculate the pool shares for the new deposit
    if (oldShares != 0) {
      // shares = stake * oldShares / oldBalance
      shares = (_stakeAmount * oldShares) / oldBalance;
    } else {
      // if no shares exist, just assign 1,000 shares (it's arbitrary)
      shares = 10**3;
    }

    // Transfer shares to caller
    _mint(msg.sender, shares);
    emit Deposit(msg.sender, _stakeAmount, shares);
  }
// Solidity 0.8.9
/**
 * @dev Burn some pool shares and claim the underlying tokens
 * @param _shareAmount The number of shares to burn
 * @return tokens The number of underlying tokens returned
 */
function burn(uint256 _shareAmount) external returns (uint256 tokens) {
    require(balanceOf(msg.sender) >= _shareAmount, "burn: insufficient shares");

    // TODO: Extract
    // Calculate the user's share of the underlying balance
    uint256 balance = stakedToken.balanceOf(address(this));
    tokens = (_shareAmount * balance) / totalSupply();

    // Burn the caller's shares before anything else
    _burn(msg.sender, _shareAmount);

    // Calculate the fee for burning
    uint256 fee = getBurnFee(tokens);
    if (fee != 0) {
      tokens -= fee;
      stakedToken.safeTransfer(feePayee, fee);
      emit Fee(fee);
    }

    // Transfer underlying tokens back to caller
    stakedToken.safeTransfer(msg.sender, tokens);
    emit Payout(msg.sender, tokens, _shareAmount);
  }
// Solidity 0.6.12
/**
 * @notice emergency functoin to withdraw LP tokens and forego harvest rewards. Important to protect users LP tokens
 */
function emergencyWithdraw() public {
        address msgSender = _msgSender();
        UserInfo storage user = userInfo[msgSender];
        farmInfo.lpToken.safeTransfer(address(msgSender), user.amount);
        emit EmergencyWithdraw(msgSender, user.amount);
        if (user.amount > 0) {
            factory.userLeftFarm(msgSender);
            farmInfo.numFarmers = farmInfo.numFarmers.sub(1);
        }
        user.amount = 0;
        user.rewardDebt = 0;
    }
// Solidity 0.8.9
/**
 * @dev Relay an index update that has been signed by an authorized proposer.
 * The signature provided must satisfy two criteria:
 * (1) the signature must be a valid EIP-712 signature for the proposal; and
 * (2) the signer must have the "PROPOSER" role.
 * @notice See https://docs.ethers.io/v5/api/signer/#Signer-signTypedData
 * @param relayed The relayed proposal
 * @param signature An EIP-712 signature for the proposal
 * @param signer The address of the EIP-712 signature provider
 * @return bond The bond amount claimable via successful dispute
 * @return proposalId The unique ID of the proposal
 * @return expiresAt The time at which the proposal is no longer disputable
 */
function relay(
    Proposal calldata relayed,
    bytes calldata signature,
    address signer
  )
    external
    onlySignedProposals(relayed, signature, signer)
    returns (
      uint256 bond,
      bytes32 proposalId,
      uint32 expiresAt
    )
  {
    proposalId = _proposalId(relayed.timestamp, relayed.value, relayed.data);
    require(proposal[proposalId].timestamp == 0, "duplicate proposal");

    Index storage _index = index[relayed.indexId];
    require(_index.disputesOutstanding < 3, "index ineligible for proposals");
    require(
      _index.lastUpdated < relayed.timestamp,
      "must be later than most recent proposal"
    );

    bond = _index.bondAmount;
    expiresAt = uint32(block.timestamp) + _index.disputePeriod;

    proposal[proposalId] = relayed;
    _index.lastUpdated = relayed.timestamp;

    _issueRewards(relayed.indexId, msg.sender);
    emit Relayed(relayed.indexId, proposalId, relayed, msg.sender, bond);
  }
// Solidity 0.8.9
/**
 * @dev Disputes a proposal prior to its expiration. This causes a bond to be
 * posted on behalf of DAOracle stakers and an equal amount to be pulled from
 * the caller.
 * @notice This actually requests, proposes, and disputes with UMA's SkinnyOO
 * which sends the bonds and disputed proposal to UMA's DVM for settlement by
 * way of governance vote. Voters follow the specification of the DAOracle's
 * approved UMIP to determine the correct value. Once the outcome is decided,
 * the SkinnyOO will callback to this contract's `priceSettled` function.
 * @param proposalId the identifier of the proposal being disputed
 */
function dispute(bytes32 proposalId) external {
    Proposal storage _proposal = proposal[proposalId];
    Index storage _index = index[_proposal.indexId];

    require(proposal[proposalId].timestamp != 0, "proposal doesn't exist");
    require(
      !isDisputed[proposalId] &&
        block.timestamp < proposal[proposalId].timestamp + _index.disputePeriod,
      "proposal already disputed or expired"
    );
    isDisputed[proposalId] = true;

    _index.dispute(_proposal, oracle, externalIdentifier);
    emit Disputed(_proposal.indexId, proposalId, msg.sender);
  }
// Solidity 0.8.9
/**
 * @dev External callback for UMA's SkinnyOptimisticOracle. Fired whenever a
 * disputed proposal has been settled by the DVM, regardless of outcome.
 * @notice This is always called by the UMA SkinnyOO contract, not an EOA.
 * @param - identifier, ignored
 * @param timestamp The timestamp of the proposal
 * @param ancillaryData The data field from the proposal
 * @param request The entire SkinnyOptimisticOracle Request object
 */
function priceSettled(
    bytes32, /** identifier */
    uint32 timestamp,
    bytes calldata ancillaryData,
    SkinnyOptimisticOracleInterface.Request calldata request
  ) external onlyRole(ORACLE) {
    bytes32 id = _proposalId(
      timestamp,
      request.proposedPrice,
      bytes32(ancillaryData)
    );
    Proposal storage relayed = proposal[id];
    Index storage _index = index[relayed.indexId];

    _index.bondsOutstanding -= request.bond;
    _index.disputesOutstanding--;
    isDisputed[id] = false;

    if (relayed.value != request.resolvedPrice) {
      // failed proposal, slash pool to recoup lost bond
      pool[request.currency].slash(_index.bondAmount, address(this));
    } else {
      // successful proposal, return bond to sponsor
      request.currency.safeTransfer(_index.sponsor, request.bond);

      // sends the rest of the funds received to the staking pool
      request.currency.safeTransfer(
        address(pool[request.currency]),
        request.currency.balanceOf(address(this))
      );
    }

    emit Settled(relayed.indexId, id, relayed.value, request.resolvedPrice);
  }
// Solidity 0.8.9
/**
 * @dev Adds or updates a index. Can only be called by managers.
 * @param bondToken The token to be used for bonds
 * @param bondAmount The quantity of tokens to offer for bonds
 * @param indexId The price index identifier
 * @param disputePeriod The proposal dispute window
 * @param floor The starting portion of rewards payable to reporters
 * @param ceiling The maximum portion of rewards payable to reporters
 * @param tilt The rate of change from floor to ceiling per second
 * @param drop The number of reward tokens to drip (per second)
 * @param creatorAmount The portion of rewards payable to the methodologist
 * @param creatorAddress The recipient of the methodologist's rewards
 * @param sponsor The provider of funding for bonds and rewards
 */
function configureIndex(
    IERC20 bondToken,
    uint256 bondAmount,
    bytes32 indexId,
    uint32 disputePeriod,
    uint64 floor,
    uint64 ceiling,
    uint64 tilt,
    uint256 drop,
    uint64 creatorAmount,
    address creatorAddress,
    address sponsor
  ) external onlyRole(MANAGER) {
    Index storage _index = index[indexId];

    _index.bondToken = bondToken;
    _index.bondAmount = bondAmount;
    _index.lastUpdated = _index.lastUpdated == 0
      ? uint32(block.timestamp)
      : _index.lastUpdated;

    _index.drop = drop;
    _index.ceiling = ceiling;
    _index.tilt = tilt;
    _index.floor = floor;
    _index.creatorAmount = creatorAmount;
    _index.creatorAddress = creatorAddress;
    _index.disputePeriod = disputePeriod == 0
      ? defaultDisputePeriod
      : disputePeriod;
    _index.sponsor = sponsor == address(0)
      ? address(_index.deploySponsorPool())
      : sponsor;

    if (address(pool[bondToken]) == address(0)) {
      _createPool(_index);
    }

    emit IndexConfigured(indexId, bondToken);
  }
// Solidity 0.6.12
/**
 * @notice handle approvals of tokens that require approving from a base of 0
 * @param token - the token we're approving
 * @param spender - entity the owner (sender) is approving to spend his tokens
 * @param amount - number of tokens being approved
 */
function safeApprove(IERC20 token, address spender, uint amount) internal returns (bool) {
        uint currentAllowance = token.allowance(address(this), spender);

        // Do nothing if allowance is already set to this value
        if(currentAllowance == amount) {
            return true;
        }

        // If approval is not zero reset it to zero first
        if(currentAllowance != 0) {
            return token.approve(spender, 0);
        }

        // do the actual approval
        return token.approve(spender, amount);
    }
// Solidity 0.6.12
/**
 * @notice Create a new CRP
 * @dev emits a LogNewCRP event
 * @param factoryAddress - the BFactory instance used to create the underlying pool
 * @param poolParams - struct containing the names, tokens, weights, balances, and swap fee
 * @param rights - struct of permissions, configuring this CRP instance (see above for definitions)
 */
function newCrp(
        address factoryAddress,
        ConfigurableRightsPool.PoolParams calldata poolParams,
        RightsManager.Rights calldata rights
    )
        external
        returns (ConfigurableRightsPool)
    {
        require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ERR_TOO_FEW_TOKENS");

        // Arrays must be parallel
        require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, "ERR_START_BALANCES_MISMATCH");
        require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, "ERR_START_WEIGHTS_MISMATCH");

        ConfigurableRightsPool crp = new ConfigurableRightsPool(
            factoryAddress,
            poolParams,
            rights
        );

        emit LogNewCrp(msg.sender, address(crp));

        _isCrp[address(crp)] = true;
        // The caller is the controller of the CRP
        // The CRP will be the controller of the underlying Core BPool
        crp.setController(msg.sender);

        return crp;
    }
// Solidity 0.6.12
/**
 * @notice Create a new ESP
 * @dev emits a LogNewESP event
 * @param factoryAddress - the BFactory instance used to create the underlying pool
 * @param poolParams - CRP pool parameters
 * @param rights - struct of permissions, configuring this CRP instance (see above for definitions)
 */
function newEsp(
        address factoryAddress,
        ConfigurableRightsPool.PoolParams calldata poolParams,
        RightsManager.Rights calldata rights
    )
        external
        returns (ElasticSupplyPool)
    {
        require(poolParams.constituentTokens.length >= BalancerConstants.MIN_ASSET_LIMIT, "ERR_TOO_FEW_TOKENS");

        // Arrays must be parallel
        require(poolParams.tokenBalances.length == poolParams.constituentTokens.length, "ERR_START_BALANCES_MISMATCH");
        require(poolParams.tokenWeights.length == poolParams.constituentTokens.length, "ERR_START_WEIGHTS_MISMATCH");

        ElasticSupplyPool esp = new ElasticSupplyPool(
            factoryAddress,
            poolParams,
            rights
        );

        emit LogNewEsp(msg.sender, address(esp));

        _isEsp[address(esp)] = true;
        esp.setController(msg.sender);

        return esp;
    }
// Solidity 0.8.7
/**
 * Command Hash helper.
 *
 * Accepts alphanumeric characters, hyphens, periods, and underscores.
 * Returns a keccak256 hash of the lowercase command.
 */
function _commandHash(string memory str) private pure returns (bytes32){
    bytes memory b = bytes(str);

    for (uint i; i<b.length; i++){
      bytes1 char = b[i];

      require (
        (char >= 0x30 && char <= 0x39) || //0-9
        (char >= 0x41 && char <= 0x5A) || //A-Z
        (char >= 0x61 && char <= 0x7A) || //a-z
        (char == 0x2D) || //-
        (char == 0x2E) || //.
        (char == 0x5F) //_
      , "Command contains invalid characters.");
    }

    bytes memory bLower = new bytes(b.length);

    for (uint i = 0; i < b.length; i++) {
      if ((uint8(b[i]) >= 65) && (uint8(b[i]) <= 90)) {
        // Uppercase character
        bLower[i] = bytes1(uint8(b[i]) + 32);
      } else {
        bLower[i] = b[i];
      }
    }

    return keccak256(abi.encode(string(bLower)));
  }
// Solidity 0.8.7
/**
 * Update a command.
 *
 * Requires ownership of token.
 */
function update(string memory _command, string memory _tokenURI) public {
    bytes32 _cmd = _commandHash(_command);
    uint tokenID = _commands[_cmd];
    require(tokenID > 0, "Command not found.");
    require(ownerOf(tokenID) == msg.sender, "Only the owner can update the token.");
    require(!_frozen[tokenID], "Token is frozen and cannot be updated.");

    _setTokenURI(tokenID, _tokenURI);
  }
// Solidity 0.8.7
/**
 * Freeze a command.
 *
 * Requires ownership of token.
 */
function freeze(string memory _command) public {
    bytes32 _cmd = _commandHash(_command);
    uint tokenID = _commands[_cmd];
    require(tokenID > 0, "Command not found.");
    require(ownerOf(tokenID) == msg.sender, "Only the owner can freeze the token.");
    require(!_frozen[tokenID], "Already frozen.");

    _frozen[tokenID] = true;
  }
// Solidity 0.8.4
// # Minting Helpers
function _safeMintQuantity(address to, uint quantity) private {
    uint fromTokenId = _totalMintedCount + 1;
    uint toTokenId = _totalMintedCount + quantity + 1;
    _totalMintedCount += quantity;
    for (uint i = fromTokenId; i < toTokenId; i++) {
      _safeMint(to, i);
    }
  }
// Solidity 0.8.4
// # Sale Mint
function presaleMint(uint[] calldata sacredDevilTokenIds, address to) external
  {
    uint quantity = sacredDevilTokenIds.length;
    _requireNotSoldOut();
    require( 
      // solhint-disable-next-line not-rely-on-time
      block.timestamp < PUBLIC_SALE_OPEN_TIME,
      "Presale has ended"
    );
    _requireSaleNotPaused();
    _requireValidQuantity(quantity);
    _requireEnoughSupplyRemaining(quantity);
    // Check the caller passed Sacred Devil token IDs that
    // - Caller owns the corresponding Sacred Devil tokens
    // - The Sacred Devil token ID has not been used before
    for (uint i = 0; i < quantity; i++) {
      uint256 sdTokenId = sacredDevilTokenIds[i];
      address ownerOfSDToken = IERC721(DEVILS_CONTRACT_ADDRESS).ownerOf(sdTokenId);
      require(
        ownerOfSDToken == msg.sender,
        string(abi.encodePacked("You do not own LOSD#", Strings.toString(sdTokenId)))
      );
      require(
        claimedDevils[sdTokenId] == false,
        string(abi.encodePacked("Already minted with LOSD#", Strings.toString(sdTokenId)))
      );
      claimedDevils[sdTokenId] = true;
    }
    _saleMintedCount += quantity;
    _safeMintQuantity(to, quantity);
  }