lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.26
/**
 * @dev Gets the price for the amount specified of the given asset.
 */
function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory)  {
        (Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
        if (err != Error.NO_ERROR) {
            return (err, Exp({mantissa: 0}));
        }

        if (isZeroExp(assetPrice)) {
            return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
        }

        return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth
    }
// Solidity 0.4.26
/**
 * @dev Gets the price for the amount specified of the given asset multiplied by the current
 *      collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth).
 *      We will group this as `(oraclePrice * collateralRatio) * assetAmountWei`
 */
function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory)  {
        Error err;
        Exp memory assetPrice;
        Exp memory scaledPrice;
        (err, assetPrice) = fetchAssetPrice(asset);
        if (err != Error.NO_ERROR) {
            return (err, Exp({mantissa: 0}));
        }

        if (isZeroExp(assetPrice)) {
            return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0}));
        }

        // Now, multiply the assetValue by the collateral ratio
        (err, scaledPrice) = mulExp(collateralRatio, assetPrice);
        if (err != Error.NO_ERROR) {
            return (err, Exp({mantissa: 0}));
        }

        // Get the price for the given asset amount
        return mulScalar(scaledPrice, assetAmount);
    }
// Solidity 0.4.26
/**
 * @dev Calculates the origination fee added to a given borrowAmount
 *      This is simply `(1 + originationFee) * borrowAmount`
 *
 *      TODO: Track at what magnitude this fee rounds down to zero?
 */
function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) {
        // When origination fee is zero, the amount with fee is simply equal to the amount
        if (isZeroExp(originationFee)) {
            return (Error.NO_ERROR, borrowAmount);
        }

        (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne}));
        if (err0 != Error.NO_ERROR) {
            return (err0, 0);
        }

        (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount);
        if (err1 != Error.NO_ERROR) {
            return (err1, 0);
        }

        return (Error.NO_ERROR, truncate(borrowAmountWithFee));
    }
// Solidity 0.4.26
/**
 * @dev fetches the price of asset from the PriceOracle and converts it to Exp
 * @param asset asset whose price should be fetched
 */
function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) {
        if (oracle == address(0)) {
            return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0}));
        }

        PriceOracleInterface oracleInterface = PriceOracleInterface(oracle);
        uint priceMantissa = oracleInterface.assetPrices(asset);

        return (Error.NO_ERROR, Exp({mantissa: priceMantissa}));
    }
// Solidity 0.4.26
/**
 * @dev Gets the amount of the specified asset given the specified Eth value
 *      ethValue / oraclePrice = assetAmountWei
 *      If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0)
 */
function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) {
        Error err;
        Exp memory assetPrice;
        Exp memory assetAmount;

        (err, assetPrice) = fetchAssetPrice(asset);
        if (err != Error.NO_ERROR) {
            return (err, 0);
        }

        (err, assetAmount) = divExp(ethValue, assetPrice);
        if (err != Error.NO_ERROR) {
            return (err, 0);
        }

        return (Error.NO_ERROR, truncate(assetAmount));
    }
// Solidity 0.4.26
/**
 * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
 * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
 * @param newPendingAdmin New pending admin.
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 *
 * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address?
 */
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
        }

        // save current value, if any, for inclusion in log
        address oldPendingAdmin = pendingAdmin;
        // Store pendingAdmin = newPendingAdmin
        pendingAdmin = newPendingAdmin;

        emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice Set new oracle, who can set asset prices
 * @dev Admin function to change oracle
 * @param newOracle New oracle address
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _setOracle(address newOracle) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK);
        }

        // Verify contract at newOracle address supports assetPrices call.
        // This will revert if it doesn't.
        PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle);
        oracleInterface.assetPrices(address(0));

        address oldOracle = oracle;

        // Store oracle = newOracle
        oracle = newOracle;

        emit NewOracle(oldOracle, newOracle);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice returns the liquidity for given account.
 *         a positive result indicates ability to borrow, whereas
 *         a negative result indicates a shortfall which may be liquidated
 * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18
 *      note: this includes interest trued up on all balances
 * @param account the account to examine
 * @return signed integer in terms of eth-wei (negative indicates a shortfall)
 */
function getAccountLiquidity(address account) public view returns (int) {
        (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account);
        require(err == Error.NO_ERROR);

        if (isZeroExp(accountLiquidity)) {
            return -1 * int(truncate(accountShortfall));
        } else {
            return int(truncate(accountLiquidity));
        }
    }
// Solidity 0.4.26
/**
 * @notice return supply balance with any accumulated interest for `asset` belonging to `account`
 * @dev returns supply balance with any accumulated interest for `asset` belonging to `account`
 * @param account the account to examine
 * @param asset the market asset whose supply balance belonging to `account` should be checked
 * @return uint supply balance on success, throws on failed assertion otherwise
 */
function getSupplyBalance(address account, address asset) view public returns (uint) {
        Error err;
        uint newSupplyIndex;
        uint userSupplyCurrent;

        Market storage market = markets[asset];
        Balance storage supplyBalance = supplyBalances[account][asset];

        // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent
        (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber());
        require(err == Error.NO_ERROR);

        // Use newSupplyIndex and stored principal to calculate the accumulated balance
        (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex);
        require(err == Error.NO_ERROR);

        return userSupplyCurrent;
    }
// Solidity 0.4.26
/**
 * @notice Supports a given market (asset) for use with Lendf.Me
 * @dev Admin function to add support for a market
 * @param asset Asset to support; MUST already have a non-zero price set
 * @param interestRateModel InterestRateModel to use for the asset
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
        }

        (Error err, Exp memory assetPrice) = fetchAssetPrice(asset);
        if (err != Error.NO_ERROR) {
            return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED);
        }

        if (isZeroExp(assetPrice)) {
            return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK);
        }

        // Set the interest rate model to `modelAddress`
        markets[asset].interestRateModel = interestRateModel;

        // Append asset to collateralAssets if not set
        addCollateralMarket(asset);

        // Set market isSupported to true
        markets[asset].isSupported = true;

        // Default supply and borrow index to 1e18
        if (markets[asset].supplyIndex == 0) {
            markets[asset].supplyIndex = initialInterestIndex;
        }

        if (markets[asset].borrowIndex == 0) {
            markets[asset].borrowIndex = initialInterestIndex;
        }

        emit SupportedMarket(asset, interestRateModel);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice Suspends a given *supported* market (asset) from use with Lendf.Me.
 *         Assets in this state do count for collateral, but users may only withdraw, payBorrow,
 *         and liquidate the asset. The liquidate function no longer checks collateralization.
 * @dev Admin function to suspend a market
 * @param asset Asset to suspend
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _suspendMarket(address asset) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK);
        }

        // If the market is not configured at all, we don't want to add any configuration for it.
        // If we find !markets[asset].isSupported then either the market is not configured at all, or it
        // has already been marked as unsupported. We can just return without doing anything.
        // Caller is responsible for knowing the difference between not-configured and already unsupported.
        if (!markets[asset].isSupported) {
            return uint(Error.NO_ERROR);
        }

        // If we get here, we know market is configured and is supported, so set isSupported to false
        markets[asset].isSupported = false;

        emit SuspendedMarket(asset);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice Sets the origination fee (which is a multiplier on new borrows)
 * @dev Owner function to set the origination fee
 * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _setOriginationFee(uint originationFeeMantissa) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK);
        }

        // Save current value so we can emit it in log.
        Exp memory oldOriginationFee = originationFee;

        originationFee = Exp({mantissa: originationFeeMantissa});

        emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice Sets the interest rate model for a given market
 * @dev Admin function to set interest rate model
 * @param asset Asset to support
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK);
        }

        // Set the interest rate model to `modelAddress`
        markets[asset].interestRateModel = interestRateModel;

        emit SetMarketInterestRateModel(asset, interestRateModel);

        return uint(Error.NO_ERROR);
    }
// Solidity 0.4.26
/**
 * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows)
 * @dev withdraws `amount` of `asset` from equity  for asset, enforcing amount <= cash - (supply + borrows)
 * @param asset asset whose equity should be withdrawn
 * @param amount amount of equity to withdraw; must not exceed equity available
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _withdrawEquity(address asset, uint amount) public returns (uint) {
        // Check caller = admin
        if (msg.sender != admin) {
            return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK);
        }

        // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply.
        uint cash = getCash(asset);
        (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply);
        if (err0 != Error.NO_ERROR) {
            return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY);
        }

        if (amount > equity) {
            return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION);
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        // We ERC-20 transfer the asset out of the protocol to the admin
        Error err2 = doTransferOut(asset, admin, amount);
        if (err2 != Error.NO_ERROR) {
            // This is safe since it's our first interaction and it didn't do anything if it failed
            return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED);
        }

        //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner)
        emit EquityWithdrawn(asset, equity, amount, admin);

        return uint(Error.NO_ERROR); // success
    }
// Solidity 0.4.26
/**
 * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18.
 *         This includes any accumulated interest thus far but does NOT actually update anything in
 *         storage
 * @dev Gets ETH values of accumulated supply and borrow balances
 * @param userAddress account for which to sum values
 * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details),
 *          sum ETH value of supplies scaled by 10e18,
 *          sum ETH value of borrows scaled by 10e18)
 */
function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) {
        (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress);
        if (err != Error.NO_ERROR) {

            return (uint(err), 0, 0);
        }

        return (0, supplyValue, borrowValue);
    }
// Solidity 0.4.26
/**
 * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow`
 */
function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal {
        // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter,
        // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter);
        emit BorrowLiquidated(localResults.targetAccount,
            localResults.assetBorrow,
            localResults.startingBorrowBalance_TargetUnderwaterAsset,
            localResults.currentBorrowBalance_TargetUnderwaterAsset,
            localResults.closeBorrowAmount_TargetUnderwaterAsset,
            localResults.updatedBorrowBalance_TargetUnderwaterAsset,
            localResults.liquidator,
            localResults.assetCollateral,
            localResults.startingSupplyBalance_TargetCollateralAsset,
            localResults.currentSupplyBalance_TargetCollateralAsset,
            localResults.seizeSupplyAmount_TargetCollateralAsset,
            localResults.updatedSupplyBalance_TargetCollateralAsset);
    }
// Solidity 0.8.7
/**
 * @dev This Hook will randomly add a token to a clan by linking the Token with clanId using `_tokenClanId`
 * Requirements:
 *  - Max clan members is 2222 during mint and user cant change clan only after mint is closed.
 */
function _onMintAddTokenToRandomClan(uint256 tokenId)
        private
        returns (bool)
    {
        uint256 _random = _generateRandom(tokenId);

        uint256 availableClansCount = availableClans.length;
        uint256 availableClanIndex = _random % availableClansCount;

        uint8 _clanId = availableClans[availableClanIndex];
        _tokenClanId[tokenId] = _clanId;
        clanMemberCount[_clanId]++;

        if (clanMemberCount[_clanId] == 2222) {
            // swap the clan reached maximum count with the last element;
            availableClans[availableClanIndex] = availableClans[
                availableClansCount - 1
            ];
            // delete the last element which will be the swapped element;
            availableClans.pop();
        }
        return true;
    }
// Solidity 0.6.12
// NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer
function cancelProposal(uint256 proposalId) external nonReentrant {
        Proposal storage proposal = proposals[proposalId];
        require(proposal.flags[0] == 0, "sponsored");
        require(proposal.flags[3] == 0, "cancelled");
        require(msg.sender == proposal.proposer, "!proposer");
        proposal.flags[3] = 1; // cancelled
       
        unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered);
        
        emit CancelProposal(proposalId, msg.sender);
    }
// Solidity 0.4.25
///Airdrop's function
function airDrop ( address contractObj,
						address   tokenRepo,
						address[] airDropDesinationAddress,
						uint[] amounts) public onlyOwner{
			for( uint i = 0 ; i < airDropDesinationAddress.length ; i++ ) {

				ERC20(contractObj).transferFrom( tokenRepo, airDropDesinationAddress[i],amounts[i]);
			}
	   }
// Solidity 0.8.7
// finish round logic -----------------------------------------------------
// ------------------------------------------------------------------------
function saveRoundHash() external isActive {
        LotteryRound storage round = history[roundNumber];
        require(round.hash == bytes32(0), "Hash already saved");
        require(block.number > round.endBlock, "Current round is not finished");
        bytes32 bhash = blockhash(round.endBlock);
        require(bhash != bytes32(0), "Too far from end round block");

        round.hash = bhash;
        emit HashSaved(bhash, roundNumber);
    }
// Solidity 0.4.25
/**
 *   @return true if the transfer was successful
 */
function transfer(address _to, uint256 _amount) public returns(bool) {
        if(msg.sender == _to) {return POSMint();}
        balances[msg.sender] = balances[msg.sender].sub(_amount);
        balances[_to] = balances[_to].add(_amount);
        emit Transfer(msg.sender, _to, _amount);
        if(transferSt[msg.sender].length > 0) {delete transferSt[msg.sender];}
        uint64 _now = uint64(now);
        transferSt[msg.sender].push(transferStruct(uint128(balances[msg.sender]),_now));
        transferSt[_to].push(transferStruct(uint128(_amount),_now));
        return true;
    }
// Solidity 0.5.15
// callable by anyone
function update_twap()
        public
    {
        (uint256 sell_token_priceCumulative, uint32 blockTimestamp) =
            UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0);
        uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired

        // ensure that at least one full period has passed since the last update
        require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED');

        // overflow is desired
        priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed));
        priceCumulativeLastSell = sell_token_priceCumulative;


        if (uniswap_pair2 != address(0)) {
            // two hop
            (uint256 buy_token_priceCumulative, ) =
                UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0);
            priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed));

            priceCumulativeLastBuy = buy_token_priceCumulative;
        }

        twap_counter = twap_counter.add(1);

        blockTimestampLast = blockTimestamp;
    }
// Solidity 0.8.4
/***********************
 + Swap wrappers        +
 ***********************/
function swapExactETHForTokens(
    Swap calldata _swap,
    uint256 _bribe
  ) external payable {
    deposit(_bribe);

    require(_swap.path[0] == WETH, 'MistXRouter: INVALID_PATH');
    uint amountIn = msg.value - _bribe;
    IWETH(WETH).deposit{value: amountIn}();
    assert(IWETH(WETH).transfer(pairFor(_swap.path[0], _swap.path[1]), amountIn));
    uint balanceBefore = IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to);
    _swapSupportingFeeOnTransferTokens(_swap.path, _swap.to);
    require(
      IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to) - balanceBefore >= _swap.amount1,
      'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT'
    );
  }
// Solidity 0.8.7
/**
 * Buy numbers of NFT in one transaction.
 * It will also increase the number of NFT buyer has bought.
 */
function buyBatch(uint256 amount) public payable 
        onlyOpened
        onlyDuringPresale 
        onlyAllowedBuyer(amount) 
        onlyPayEnoughEth(amount)
        returns (uint256[] memory) {
        require(amount >= 1, "Presale: batch size should larger than 0.");
        _sold_ += amount;
        _buyers_[msg.sender].bought += amount;
        return _minterMintable_.batchMint(msg.sender, amount);
    }
// Solidity 0.4.23
/**
 * Execute a message call from the proxy contract
 *
 * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access
 * @param dest Address to which the call will be sent
 * @param howToCall Which kind of call to make
 * @param calldata Calldata to send
 * @return Result of the call (success or failure)
 */
function proxy(address dest, HowToCall howToCall, bytes calldata)
        public
        returns (bool result)
    {
        require(msg.sender == user || (!revoked && registry.contracts(msg.sender)));
        if (howToCall == HowToCall.Call) {
            result = dest.call(calldata);
        } else if (howToCall == HowToCall.DelegateCall) {
            result = dest.delegatecall(calldata);
        }
        return result;
    }