lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) {
        CompoundSubscriptions.CompoundHolder memory holder;

        holder= subscriptionsContract.getHolder(_user);

        uint currRatio = getSafetyRatio(_user);

        if (_method == Method.Repay) {
            return (currRatio < holder.maxRatio, currRatio);
        } else if (_method == Method.Boost) {
            return (currRatio > holder.minRatio, currRatio);
        }
    }
// Solidity 0.4.19
/* For The Minter to give CWC to a client */
function minterGivesCWC(address _to, uint _value) public {
        require(isMinter[msg.sender]); //minters are the sales items: UET, DET, ...
        require(!isMinter[_to] && _to != owner); //to a client
        balances[_to] = balances[_to].add(_value);
        MinterGaveCWC(msg.sender, _to, _value);
    }
// Solidity 0.4.19
/* ERC223 transfer CWCs with data */
function transfer(address _to, uint _value, bytes _data) public {
        uint codeLength;

        assembly {
            codeLength := extcodesize(_to)
        }

        balances[msg.sender] = balances[msg.sender].sub(_value);
        
        if(!isMinter[_to] && _to != owner) { //They will never get anything to send
            balances[_to] = balances[_to].add(_value);
        }

        if(codeLength>0) {
            CWC_ReceiverInterface receiver = CWC_ReceiverInterface(_to);
            receiver.CWCfallback(msg.sender, _value, _data);
        }
	    // Generate an event for the client
        Transfer(msg.sender, _to, _value, _data);
        // Returning CWCs
        if(_to == owner) {
            CWCreturnTransaction(msg.sender, _value); // <====== Entry to CWC Return
        }
    }
// Solidity 0.4.19
/* ERC223 transfer CWCs w/o data for ERC20 compatibility */
function transfer(address _to, uint _value) public {
        uint codeLength;
        bytes memory empty;

        assembly {
            codeLength := extcodesize(_to)
        }

        balances[msg.sender] = balances[msg.sender].sub(_value);

        if(!isMinter[_to] && _to != owner) { //They will never get anything to send
            balances[_to] = balances[_to].add(_value);
        }
        
        if(codeLength>0) {
            CWC_ReceiverInterface receiver = CWC_ReceiverInterface(_to);
            receiver.CWCfallback(msg.sender, _value, empty);
        }
	    // Generate an event for the client
        Transfer(msg.sender, _to, _value, empty);
        // Returning CWCs
        if(_to == owner) {
            CWCreturnTransaction(msg.sender, _value); // <====== Entry to CWC Return
        }
    }
// Solidity 0.4.19
//================================ CWC Return Transaction ==================================//
function CWCreturnTransaction(address from, uint amount) private {
        require(verifiedUsersOnlyMode==false || verifiedUsers[from]==true);
        require(!pauseCWC);
        require(amount>minCWCsPerReturnMoreThan && amount<maxCWCsPerReturnLessThan);
        
        if (oraclize_getPrice("URL") > this.balance) {
            needsEther("Oraclize query for CWC return was NOT sent, please add some ETH to cover for the query fee");
            pauseCWC=true;
            revert();
        } 
        else {
            //Expectation: CWC_Sale for Ask (a) and CWC_Return for Bid (b)
            tickerQueryData = strConcat("1,", "CWC,", "0x", addressToAsciiString(from), ",");
            tickerQueryData = strConcat(tickerQueryData, uint2str(amount));
            bytes32 queryId = oraclize_query("URL", tickerQuery, tickerQueryData);
            tickerQueryIds[queryId] = true;
            tickerQueryPurpose[queryId] = 2; //1 for CWC sale; 2 for CWC return
            waitingSeller[queryId] = from;
            cwcPaid[queryId] = amount;
            receivedCWCreturn(waitingSeller[queryId], cwcPaid[queryId]);
            newTickerQuery("Called Oraclize for CWC return. Waiting…", queryId);
        }
    }
// Solidity 0.6.12
// _migrateCashLP migrates MICv1 LP tokens into MICv2 LP and returns the amount of converted MICv1.
function _migrateCashLP()
        internal
        onlyOneBlock
        returns (uint256)
    {
        require(block.timestamp <= endTime, 'CashLpMigrator: redemption period ended');
        uint256 amount = IERC20(lp_old).balanceOf(msg.sender);
        require(amount > 0, 'CashLpMigrator: cannot exchange zero amount');

        //Transfer LPv1 to the contract
        IERC20(lp_old).safeTransferFrom(msg.sender, address(this), amount);

        //Remove liquidity, which puts USDT and MICv1 in the contract
        IERC20(lp_old).safeApprove(univ2Router2, 0);
        IERC20(lp_old).safeApprove(univ2Router2, amount);
        IUniswapV2Router(univ2Router2).removeLiquidity(
                cash_old,
                usdt,
                amount,
                0,
                0,
                address(this),
                now + 60
            );

        //Exchange balance of MICv1 for MICv2
        uint256 cash_old_amount = IERC20(cash_old).balanceOf(address(this));
        IERC20(cash_old).safeApprove(cashExchange, 0);
        IERC20(cash_old).safeApprove(cashExchange, cash_old_amount);
        CashExchange(cashExchange).exchangeCash(cash_old_amount);
        
        uint256 usdt_amount = IERC20(usdt).balanceOf(address(this));
        uint256 cash_new_amount = IERC20(cash_new).balanceOf(address(this));
            
        //Add USDT + MICv2 liquidity to Curve, which puts LPv2 in the contract
        IERC20(usdt).safeApprove(curveDepositer, 0);
        IERC20(usdt).safeApprove(curveDepositer, usdt_amount);
        IERC20(cash_new).safeApprove(curveDepositer, 0);
        IERC20(cash_new).safeApprove(curveDepositer, cash_new_amount);
        //args are: address, [cash, dai, usdc, usdt], min_mint_amount
        ICurveMeta(curveDepositer).add_liquidity(curvePool, [cash_new_amount, 0, 0, usdt_amount], 1);
        return cash_old_amount;
    }
// Solidity 0.6.12
//Converts V1 Cash/stable LP to V2 Cash/stable LP and stakes the V2 LP tokens on behalf of the user
function migrateLockedCashLP()
        external
        onlyOneBlock
    {
        //Only need to check price if I'm locking
        uint256 cashPrice = getOraclePrice();
        require(cashPrice <= 1000000, 'Cash v1 price must be <= $1');

        uint256 convertedOldCashAmount = _migrateCashLP();

        //StakeLocked(_address, balance) stakes on behalf of _address
        //new staking contract should check the cash price before allowing people to stake locked
        //if that is the case, then I don't need to check the cash price in this contract
        uint256 stakeAmount = IERC20(lp_new).balanceOf(address(this));
        IERC20(lp_new).approve(stakingContract, stakeAmount);
        IStakingRewardsv2(stakingContract).stakeLockedFor(msg.sender, stakeAmount, convertedOldCashAmount);
    }
// Solidity 0.8.3
/**
 * @notice Send this earning to drip contract.
 */
function _forwardEarning() internal override {
        address _dripContract = IVesperPool(pool).poolRewards();
        uint256 _earned = IERC20(dripToken).balanceOf(address(this));
        // Fetches which rewardToken collects the drip
        address _growPool = IEarnDrip(_dripContract).growToken();
        // Checks that the Grow Pool supports dripToken as underlying
        require(address(IVesperPool(_growPool).token()) == dripToken, "invalid-grow-pool");

        if (!transferToDripContract && _earned != 0) {
            totalEarned += _earned;
            IVesperPool(_growPool).deposit(_earned);

            // Next rebalance call will transfer to dripContract
            transferToDripContract = true;
        } else if (transferToDripContract) {
            (, uint256 _interestFee, , , , , , ) = IVesperPool(pool).strategy(address(this));
            uint256 _growPoolShares = IERC20(_growPool).balanceOf(address(this));
            uint256 _fee = (_growPoolShares * _interestFee) / 10000;

            if (_fee != 0) {
                IERC20(_growPool).safeTransfer(feeCollector, _fee);
                _growPoolShares -= _fee;
            }
            IERC20(_growPool).safeTransfer(_dripContract, _growPoolShares);
            IEarnDrip(_dripContract).notifyRewardAmount(_growPool, _growPoolShares, dripPeriod);

            // Next rebalance call will deposit VSP to vVSP Pool
            transferToDripContract = false;
        }
    }
// Solidity 0.7.0
/**
 * Mints monster
 */
function mintmonster( string calldata message) public {
        require(saleIsActive, "Sale must be active to mint monster");
        require((totalSupply()+1) <= MAX_monster, "Purchase would exceed max supply of monster");
        require(saletoken.allowance(msg.sender, address(this)) >= monsterPrice, "This contract is not approved to spend your token" );
        saletoken.approve(walletToRecieveToken, monsterPrice);
        saletoken.transferFrom(msg.sender, walletToRecieveToken, monsterPrice);
        
        uint mintIndex = totalSupply();
            if (totalSupply() < MAX_monster) {
                super._safeMint(msg.sender, mintIndex+1);
                super._setTokenURI(mintIndex+1,message);
                emit minted(msg.sender, mintIndex+1, message);
            }
        
        // If we haven't set the starting index and this is either 1) the last saleable token or 2) the first token to be sold after
        // the end of pre-sale, set the starting index block
        if (startingIndexBlock == 0 && (totalSupply() == MAX_monster || block.timestamp >= REVEAL_TIMESTAMP)) {
            startingIndexBlock = block.number;
        } 
    }
// Solidity 0.4.24
// Calculates the Bonus Award based upon the purchase amount and the purchase period
// function calculateBonus(uint256 individuallyContributedEtherInWei) private returns(uint256 bonus_applied)
function startPreICO() public onlyOwner atStage(Stages.NOTSTARTED)
	{
		stage = Stages.PREICO;
		paused = false;
		Price_Per_Token = 10;
		BONUS = 30;
		balances[address(this)] = (TotalpresaleSupply).mul(TOKEN_DECIMALS);
		StartdatePresale = now;
		EnddatePresale = now + PresaleDays;
		emit Transfer(0, address(this), balances[address(this)]);

	}
// Solidity 0.6.12
/**
 * @notice Calculate the dy, the amount of selected token that user receives and
 * the fee of withdrawing in one token
 * @param account the address that is withdrawing
 * @param tokenAmount the amount to withdraw in the pool's precision
 * @param tokenIndex which token will be withdrawn
 * @param self Swap struct to read from
 * @return the amount of token user will receive
 */
function calculateWithdrawOneToken(
        Swap storage self,
        address account,
        uint256 tokenAmount,
        uint8 tokenIndex
    ) external view returns (uint256) {
        (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken(
            self,
            account,
            tokenAmount,
            tokenIndex,
            self.lpToken.totalSupply()
        );
        return availableTokenAmount;
    }
// Solidity 0.6.12
/**
 * @notice Calculate the price of a token in the pool with given
 * precision-adjusted balances and a particular D.
 *
 * @dev This is accomplished via solving the invariant iteratively.
 * See the StableSwap paper and Curve.fi implementation for further details.
 *
 * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)
 * x_1**2 + b*x_1 = c
 * x_1 = (x_1**2 + c) / (2*x_1 + b)
 *
 * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details.
 * @param tokenIndex Index of token we are calculating for.
 * @param xp a precision-adjusted set of pool balances. Array should be
 * the same cardinality as the pool.
 * @param d the stableswap invariant
 * @return the price of the token, in the same precision as in xp
 */
function getYD(
        uint256 a,
        uint8 tokenIndex,
        uint256[] memory xp,
        uint256 d
    ) internal pure returns (uint256) {
        uint256 numTokens = xp.length;
        require(tokenIndex < numTokens, "Token not found");

        uint256 c = d;
        uint256 s;
        uint256 nA = a.mul(numTokens);

        for (uint256 i = 0; i < numTokens; i++) {
            if (i != tokenIndex) {
                s = s.add(xp[i]);
                c = c.mul(d).div(xp[i].mul(numTokens));
                // If we were to protect the division loss we would have to keep the denominator separate
                // and divide at the end. However this leads to overflow with large numTokens or/and D.
                // c = c * D * D * D * ... overflow!
            }
        }
        c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div(
            nA.mul(numTokens)
        );

        uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA));
        uint256 yPrev;
        uint256 y = d;
        for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) {
            yPrev = y;
            y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d));
            if (y.within1(yPrev)) {
                return y;
            }
        }
        revert("Approximation did not converge");
    }
// Solidity 0.6.12
/**
 * @notice Given a set of balances and precision multipliers, return the
 * precision-adjusted balances.
 *
 * @param balances an array of token balances, in their native precisions.
 * These should generally correspond with pooled tokens.
 *
 * @param precisionMultipliers an array of multipliers, corresponding to
 * the amounts in the balances array. When multiplied together they
 * should yield amounts at the pool's precision.
 *
 * @return an array of amounts "scaled" to the pool's precision
 */
function _xp(
        uint256[] memory balances,
        uint256[] memory precisionMultipliers
    ) internal pure returns (uint256[] memory) {
        uint256 numTokens = balances.length;
        require(
            numTokens == precisionMultipliers.length,
            "Balances must match multipliers"
        );
        uint256[] memory xp = new uint256[](numTokens);
        for (uint256 i = 0; i < numTokens; i++) {
            xp[i] = balances[i].mul(precisionMultipliers[i]);
        }
        return xp;
    }
// Solidity 0.6.12
/**
 * @notice Get the virtual price, to help calculate profit
 * @param self Swap struct to read from
 * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS
 */
function getVirtualPrice(Swap storage self)
        external
        view
        returns (uint256)
    {
        uint256 d = getD(_xp(self), _getAPrecise(self));
        LPToken lpToken = self.lpToken;
        uint256 supply = lpToken.totalSupply();
        if (supply > 0) {
            return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply);
        }
        return 0;
    }
// Solidity 0.6.12
/**
 * @notice Internally calculates a swap between two tokens.
 *
 * @dev The caller is expected to transfer the actual amounts (dx and dy)
 * using the token contracts.
 *
 * @param self Swap struct to read from
 * @param tokenIndexFrom the token to sell
 * @param tokenIndexTo the token to buy
 * @param dx the number of tokens to sell. If the token charges a fee on transfers,
 * use the amount that gets transferred after the fee.
 * @return dy the number of tokens the user will get
 * @return dyFee the associated fee
 */
function _calculateSwap(
        Swap storage self,
        uint8 tokenIndexFrom,
        uint8 tokenIndexTo,
        uint256 dx,
        uint256[] memory balances
    ) internal view returns (uint256 dy, uint256 dyFee) {
        uint256[] memory multipliers = self.tokenPrecisionMultipliers;
        uint256[] memory xp = _xp(balances, multipliers);
        require(
            tokenIndexFrom < xp.length && tokenIndexTo < xp.length,
            "Token index out of range"
        );
        uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]);
        uint256 y = getY(
            _getAPrecise(self),
            tokenIndexFrom,
            tokenIndexTo,
            x,
            xp
        );
        dy = xp[tokenIndexTo].sub(y).sub(1);
        dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR);
        dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]);
    }
// Solidity 0.6.12
/**
 * @notice A simple method to calculate prices from deposits or
 * withdrawals, excluding fees but including slippage. This is
 * helpful as an input into the various "min" parameters on calls
 * to fight front-running
 *
 * @dev This shouldn't be used outside frontends for user estimates.
 *
 * @param self Swap struct to read from
 * @param account address of the account depositing or withdrawing tokens
 * @param amounts an array of token amounts to deposit or withdrawal,
 * corresponding to pooledTokens. The amount should be in each
 * pooled token's native precision. If a token charges a fee on transfers,
 * use the amount that gets transferred after the fee.
 * @param deposit whether this is a deposit or a withdrawal
 * @return if deposit was true, total amount of lp token that will be minted and if
 * deposit was false, total amount of lp token that will be burned
 */
function calculateTokenAmount(
        Swap storage self,
        address account,
        uint256[] calldata amounts,
        bool deposit
    ) external view returns (uint256) {
        uint256 a = _getAPrecise(self);
        uint256[] memory balances = self.balances;
        uint256[] memory multipliers = self.tokenPrecisionMultipliers;

        uint256 d0 = getD(_xp(balances, multipliers), a);
        for (uint256 i = 0; i < balances.length; i++) {
            if (deposit) {
                balances[i] = balances[i].add(amounts[i]);
            } else {
                balances[i] = balances[i].sub(
                    amounts[i],
                    "Cannot withdraw more than available"
                );
            }
        }
        uint256 d1 = getD(_xp(balances, multipliers), a);
        uint256 totalSupply = self.lpToken.totalSupply();

        if (deposit) {
            return d1.sub(d0).mul(totalSupply).div(d0);
        } else {
            return
                d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div(
                    FEE_DENOMINATOR.sub(
                        _calculateCurrentWithdrawFee(self, account)
                    )
                );
        }
    }
// Solidity 0.6.12
/**
 * @notice swap two tokens in the pool
 * @param self Swap struct to read from and write to
 * @param tokenIndexFrom the token the user wants to sell
 * @param tokenIndexTo the token the user wants to buy
 * @param dx the amount of tokens the user wants to sell
 * @param minDy the min amount the user would like to receive, or revert.
 * @return amount of token user received on swap
 */
function swap(
        Swap storage self,
        uint8 tokenIndexFrom,
        uint8 tokenIndexTo,
        uint256 dx,
        uint256 minDy
    ) external returns (uint256) {
        {
            IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];
            require(
                dx <= tokenFrom.balanceOf(msg.sender),
                "Cannot swap more than you own"
            );
            // Transfer tokens first to see if a fee was charged on transfer
            uint256 beforeBalance = tokenFrom.balanceOf(address(this));
            tokenFrom.safeTransferFrom(msg.sender, address(this), dx);

            // Use the actual transferred amount for AMM math
            dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance);
        }

        uint256 dy;
        uint256 dyFee;
        uint256[] memory balances = self.balances;
        (dy, dyFee) = _calculateSwap(
            self,
            tokenIndexFrom,
            tokenIndexTo,
            dx,
            balances
        );
        require(dy >= minDy, "Swap didn't result in min tokens");

        uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div(
            self.tokenPrecisionMultipliers[tokenIndexTo]
        );

        self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx);
        self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub(
            dyAdminFee
        );

        self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);

        emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);

        return dy;
    }
// Solidity 0.6.12
/**
 * @notice Update the withdraw fee for `user`. If the user is currently
 * not providing liquidity in the pool, sets to default value. If not, recalculate
 * the starting withdraw fee based on the last deposit's time & amount relative
 * to the new deposit.
 *
 * @param self Swap struct to read from and write to
 * @param user address of the user depositing tokens
 * @param toMint amount of pool tokens to be minted
 */
function updateUserWithdrawFee(
        Swap storage self,
        address user,
        uint256 toMint
    ) public {
        // If token is transferred to address 0 (or burned), don't update the fee.
        if (user == address(0)) {
            return;
        }
        if (self.defaultWithdrawFee == 0) {
            // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR
            self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR;
        } else {
            // Otherwise, calculate appropriate discount based on last deposit amount
            uint256 currentFee = _calculateCurrentWithdrawFee(self, user);
            uint256 currentBalance = self.lpToken.balanceOf(user);

            // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR /
            // ((toMint + currentBalance) * defaultWithdrawFee)
            self.withdrawFeeMultiplier[user] = currentBalance
                .mul(currentFee)
                .add(toMint.mul(self.defaultWithdrawFee))
                .mul(FEE_DENOMINATOR)
                .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee));
        }
        self.depositTimestamp[user] = block.timestamp;
    }
// Solidity 0.6.12
/**
 * @notice Burn LP tokens to remove liquidity from the pool.
 * @dev Liquidity can always be removed, even when the pool is paused.
 * @param self Swap struct to read from and write to
 * @param amount the amount of LP tokens to burn
 * @param minAmounts the minimum amounts of each token in the pool
 * acceptable for this burn. Useful as a front-running mitigation
 * @return amounts of tokens the user received
 */
function removeLiquidity(
        Swap storage self,
        uint256 amount,
        uint256[] calldata minAmounts
    ) external returns (uint256[] memory) {
        LPToken lpToken = self.lpToken;
        IERC20[] memory pooledTokens = self.pooledTokens;
        require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf");
        require(
            minAmounts.length == pooledTokens.length,
            "minAmounts must match poolTokens"
        );

        uint256[] memory balances = self.balances;
        uint256 totalSupply = lpToken.totalSupply();

        uint256[] memory amounts = _calculateRemoveLiquidity(
            self,
            balances,
            msg.sender,
            amount,
            totalSupply
        );

        for (uint256 i = 0; i < amounts.length; i++) {
            require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]");
            self.balances[i] = balances[i].sub(amounts[i]);
            pooledTokens[i].safeTransfer(msg.sender, amounts[i]);
        }

        lpToken.burnFrom(msg.sender, amount);

        emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount));

        return amounts;
    }