lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.17
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
///      to the fillResults that are being collected on the order. Both orders will be fully filled in this
///      case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
        uint256 leftMakerAssetAmountRemaining,
        uint256 leftTakerAssetAmountRemaining,
        uint256 rightMakerAssetAmountRemaining,
        uint256 rightTakerAssetAmountRemaining
    )
        private
        pure
        returns (MatchedFillResults memory matchedFillResults)
    {
        // Calculate the fully filled results for both orders.
        matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
        matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
        matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
        matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;

        return matchedFillResults;
    }
// Solidity 0.5.17
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
///      to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
///                  can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
        LibOrder.Order memory leftOrder,
        uint256 rightMakerAssetAmountRemaining,
        uint256 rightTakerAssetAmountRemaining
    )
        private
        pure
        returns (MatchedFillResults memory matchedFillResults)
    {
        matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
        matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
        matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
        // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
        // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
        // left maker asset.
        matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
            leftOrder.makerAssetAmount,
            leftOrder.takerAssetAmount,
            rightMakerAssetAmountRemaining
        );

        return matchedFillResults;
    }
// Solidity 0.4.21
/**
 * Transfer tokens from the caller to a new holder.
 * No fee with this transfer
 */
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) {
        // setup
        address _customerAddress = msg.sender;

        // make sure we have the requested tokens
        require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);

        // withdraw all outstanding dividends first
        if(myDividends(true) > 0) withdraw();

        // exchange tokens
        tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
        tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);

        // update dividend trackers
        payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
        payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);


        // fire event
        emit Transfer(_customerAddress, _toAddress, _amountOfTokens);

        // ERC20
        return true;
    }
// Solidity 0.6.4
//======================================ACTION CALLS=========================================//	
function _stake(uint256 _amount) internal {
	    
	    require(stakingEnabled, "Staking not yet initialized");
	    
		require(IERC20(UniswapV2).balanceOf(msg.sender) >= _amount, "Insufficient SWAP AFT balance");
		require(frozenOf(msg.sender) + _amount >= MINIMUM_STAKE, "Your amount is lower than the minimum amount allowed to stake");
		require(IERC20(UniswapV2).allowance(msg.sender, address(this)) >= _amount, "Not enough allowance given to contract yet to spend by user");
		
		info.users[msg.sender].staketime = now;
		info.totalFrozen += _amount;
		info.users[msg.sender].frozen += _amount;
		
		info.users[msg.sender].scaledPayout += int256(_amount * info.scaledPayoutPerToken); 
		IERC20(UniswapV2).transferFrom(msg.sender, address(this), _amount);      // Transfer liquidity tokens from the sender to this contract
		
        emit StakeEvent(msg.sender, address(this), _amount);
	}
// Solidity 0.7.6
/**
 *  @dev Mint xU3LP tokens by sending *amount* of *inputAsset* tokens
 */
function mintWithToken(uint8 inputAsset, uint256 amount)
        external
        notLocked(msg.sender)
        whenNotPaused()
    {
        require(amount > 0);
        lock(msg.sender);
        checkTwap();
        uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee);
        if (inputAsset == 0) {
            token0.safeTransferFrom(msg.sender, address(this), amount);
            _incrementWithdrawableToken0Fees(fee);
            _mintInternal(
                getToken0AmountInWei(getAmountInAsset1Terms(amount).sub(fee))
            );
        } else {
            token1.safeTransferFrom(msg.sender, address(this), amount);
            _incrementWithdrawableToken1Fees(fee);
            _mintInternal(
                getToken1AmountInWei(getAmountInAsset0Terms(amount).sub(fee))
            );
        }
    }
// Solidity 0.7.6
/**
 *  @dev Burn *amount* of xU3LP tokens to receive proportional
 *  amount of *outputAsset* tokens
 */
function burn(uint8 outputAsset, uint256 amount)
        external
        notLocked(msg.sender)
    {
        require(amount > 0);
        lock(msg.sender);
        checkTwap();
        uint256 bufferBalance = getBufferBalance();
        uint256 totalBalance = bufferBalance.add(getStakedBalance());

        uint256 proRataBalance;
        if (outputAsset == 0) {
            proRataBalance = (totalBalance.mul(getAmountInAsset0Terms(amount)))
                .div(totalSupply());
        } else {
            proRataBalance = (
                totalBalance.mul(getAmountInAsset1Terms(amount)).div(
                    totalSupply()
                )
            );
        }

        // Add swap slippage to the calculations
        uint256 proRataBalanceWithSlippage =
            proRataBalance.add(proRataBalance.div(SWAP_SLIPPAGE));

        require(
            proRataBalanceWithSlippage <= bufferBalance,
            "Insufficient exit liquidity"
        );
        super._burn(msg.sender, amount);

        // Fee is in wei (18 decimals, so doesn't need to be normalized)
        uint256 fee = Utils.calculateFee(proRataBalance, feeDivisors.burnFee);
        if (outputAsset == 0) {
            withdrawableToken0Fees = withdrawableToken0Fees.add(fee);
        } else {
            withdrawableToken1Fees = withdrawableToken1Fees.add(fee);
        }
        uint256 transferAmount = proRataBalance.sub(fee);
        transferOnBurn(outputAsset, transferAmount);
    }
// Solidity 0.7.6
// Get wanted xU3LP contract token balance - 5% of NAV
function getTargetBufferTokenBalance()
        public
        view
        returns (uint256 amount0, uint256 amount1)
    {
        (uint256 bufferAmount0, uint256 bufferAmount1) =
            getBufferTokenBalance();
        (uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance();
        amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET);
        amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET);
        // Keep 50:50 ratio
        amount0 = amount0.add(amount1).div(2);
        amount1 = amount0;
    }
// Solidity 0.7.6
/**
 * Check if token amounts match before attempting mint() or burn()
 * Uniswap contract requires deposits at a precise token ratio
 * If they don't match, swap the tokens so as to deposit as much as possible
 */
function checkIfAmountsMatchAndSwap(
        uint256 amount0ToMint,
        uint256 amount1ToMint
    ) private returns (uint256 amount0, uint256 amount1) {
        (uint256 amount0Minted, uint256 amount1Minted) =
            calculatePoolMintedAmounts(amount0ToMint, amount1ToMint);
        if (
            amount0Minted <
            amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) ||
            amount1Minted <
            amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE))
        ) {
            // calculate liquidity ratio
            uint256 mintLiquidity =
                getLiquidityForAmounts(amount0ToMint, amount1ToMint);
            uint256 poolLiquidity = getPoolLiquidity();
            int128 liquidityRatio =
                poolLiquidity == 0
                    ? 0
                    : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity));
            (amount0, amount1) = restoreTokenRatios(
                amount0ToMint,
                amount1ToMint,
                amount0Minted,
                amount1Minted,
                liquidityRatio
            );
        } else {
            (amount0, amount1) = (amount0ToMint, amount1ToMint);
        }
    }
// Solidity 0.7.6
// Migrate the current position to a new position with different ticks
function migratePosition(int24 newTickLower, int24 newTickUpper)
        external
        onlyOwnerOrManager
    {
        require(newTickLower != tickLower || newTickUpper != tickUpper);

        // withdraw entire liquidity from the position
        (uint256 _amount0, uint256 _amount1) = withdrawAll();
        // burn current position NFT
        positionManager.burn(tokenId);
        tokenId = 0;
        // set new ticks and prices
        tickLower = newTickLower;
        tickUpper = newTickUpper;
        priceLower = TickMath.getSqrtRatioAtTick(newTickLower);
        priceUpper = TickMath.getSqrtRatioAtTick(newTickUpper);

        // if amounts don't add up when minting, swap tokens
        (uint256 amount0, uint256 amount1) =
            checkIfAmountsMatchAndSwap(_amount0, _amount1);

        // mint the position NFT and deposit the liquidity
        // set new NFT token id
        tokenId = createPosition(amount0, amount1);
        emit PositionMigrated(newTickLower, newTickUpper);
    }
// Solidity 0.7.6
/**
 * Transfers asset amount when user calls burn()
 * If there's not enough balance of that asset,
 * triggers a router swap to increase the balance
 * keep token ratio in xU3LP at 50:50 after swapping
 */
function transferOnBurn(uint8 outputAsset, uint256 transferAmount) private {
        (uint256 balance0, uint256 balance1) = getBufferTokenBalance();
        if (outputAsset == 0) {
            if (balance0 < transferAmount) {
                uint256 amountIn =
                    transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(
                        balance0
                    );
                uint256 amountOut = transferAmount.sub(balance0);
                uint256 balanceFactor = Utils.sub0(balance1, amountOut).div(2);
                amountIn = amountIn.add(balanceFactor);
                amountOut = amountOut.add(balanceFactor);
                swapToken1ForToken0(amountIn, amountOut);
            }
            transferAmount = getToken0AmountInNativeDecimals(transferAmount);
            token0.safeTransfer(msg.sender, transferAmount);
        } else {
            if (balance1 < transferAmount) {
                uint256 amountIn =
                    transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub(
                        balance1
                    );
                uint256 amountOut = transferAmount.sub(balance1);
                uint256 balanceFactor = Utils.sub0(balance0, amountOut).div(2);
                amountIn = amountIn.add(balanceFactor);
                amountOut = amountOut.add(balanceFactor);
                swapToken0ForToken1(amountIn, amountOut);
            }
            transferAmount = getToken1AmountInNativeDecimals(transferAmount);
            token1.safeTransfer(msg.sender, transferAmount);
        }
    }
// Solidity 0.7.6
/**
 * Mint function which initializes the pool position
 * Must be called before any liquidity can be deposited
 */
function mintInitial(uint256 amount0, uint256 amount1)
        external
        onlyOwnerOrManager
    {
        require(tokenId == 0);
        require(amount0 > 0 || amount1 > 0);
        checkTwap();
        if (amount0 > 0) {
            token0.safeTransferFrom(msg.sender, address(this), amount0);
        }
        if (amount1 > 0) {
            token1.safeTransferFrom(msg.sender, address(this), amount1);
        }
        tokenId = createPosition(amount0, amount1);
        amount0 = getToken0AmountInWei(amount0);
        amount1 = getToken1AmountInWei(amount1);
        _mintInternal(
            getAmountInAsset1Terms(amount0).add(getAmountInAsset0Terms(amount1))
        );
        emit PositionInitialized(tickLower, tickUpper);
    }
// Solidity 0.7.6
/**
 * Creates the NFT token representing the pool position
 */
function createPosition(uint256 amount0, uint256 amount1)
        private
        returns (uint256 _tokenId)
    {
        (_tokenId, , , ) = positionManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: address(token0),
                token1: address(token1),
                fee: POOL_FEE,
                tickLower: tickLower,
                tickUpper: tickUpper,
                amount0Desired: amount0,
                amount1Desired: amount1,
                amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)),
                amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)),
                recipient: address(this),
                deadline: block.timestamp
            })
        );
    }
// Solidity 0.7.6
/**
 * @dev Unstakes a given amount of liquidity from the Uni V3 position
 * @param liquidity amount of liquidity to unstake
 * @return amount0 token0 amount unstaked
 * @return amount1 token1 amount unstaked
 */
function unstakePosition(uint128 liquidity)
        private
        returns (uint256 amount0, uint256 amount1)
    {
        (uint256 _amount0, uint256 _amount1) =
            getAmountsForLiquidity(liquidity);
        (amount0, amount1) = positionManager.decreaseLiquidity(
            INonfungiblePositionManager.DecreaseLiquidityParams({
                tokenId: tokenId,
                liquidity: liquidity,
                amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)),
                amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)),
                deadline: block.timestamp
            })
        );
    }
// Solidity 0.7.6
/*
 * Withdraw function for token0 and token1 fees
 */
function withdrawFees() external onlyOwnerOrManager {
        uint256 token0Fees =
            getToken0AmountInNativeDecimals(withdrawableToken0Fees);
        uint256 token1Fees =
            getToken1AmountInNativeDecimals(withdrawableToken1Fees);
        if (token0Fees > 0) {
            token0.safeTransfer(msg.sender, token0Fees);
            withdrawableToken0Fees = 0;
        }
        if (token1Fees > 0) {
            token1.safeTransfer(msg.sender, token1Fees);
            withdrawableToken1Fees = 0;
        }

        emit FeeWithdraw(token0Fees, token1Fees);
    }
// Solidity 0.7.6
/**
 *  @dev Withdraw until token0 or token1 balance reaches amount
 *  @param forToken0 withdraw balance for token0 (true) or token1 (false)
 *  @param amount minimum amount we want to have in token0 or token1
 */
function withdrawSingleToken(bool forToken0, uint256 amount) private {
        uint256 balance;
        uint256 unstakeAmount0;
        uint256 unstakeAmount1;
        uint256 swapAmount;
        do {
            // calculate how much we can withdraw
            (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts(
                getToken0AmountInNativeDecimals(amount),
                getToken1AmountInNativeDecimals(amount)
            );
            // withdraw both tokens
            _unstake(unstakeAmount0, unstakeAmount1);

            // swap the excess amount of token0 for token1 or vice-versa
            swapAmount = forToken0
                ? getToken1AmountInWei(unstakeAmount1)
                : getToken0AmountInWei(unstakeAmount0);
            forToken0
                ? swapToken1ForToken0(
                    swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
                    swapAmount
                )
                : swapToken0ForToken1(
                    swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)),
                    swapAmount
                );
            balance = forToken0
                ? getBufferToken0Balance()
                : getBufferToken1Balance();
        } while (balance < amount);
    }
// Solidity 0.7.6
// Returns the earliest oracle observation time
function getObservationTime() public view returns (uint32) {
        (, , uint16 index, uint16 cardinality, , , ) = pool.slot0();
        uint16 oldestObservationIndex = (index + 1) % cardinality;
        (uint32 observationTime, , , bool initialized) =
            pool.observations(oldestObservationIndex);
        if (!initialized) (observationTime, , , ) = pool.observations(0);
        return observationTime;
    }
// Solidity 0.7.6
/**
 *  Get asset 0 twap
 *  Uses Uni V3 oracle, reading the TWAP from twap period
 *  or the earliest oracle observation time if twap period is not set
 */
function getAsset0Price() public view returns (int128) {
        uint32[] memory secondsArray = new uint32[](2);
        // get earliest oracle observation time
        uint32 observationTime = getObservationTime();
        uint32 currTimestamp = uint32(block.timestamp);
        uint32 earliestObservationSecondsAgo = currTimestamp - observationTime;
        if (
            twapPeriod == 0 ||
            !Utils.lte(
                currTimestamp,
                observationTime,
                currTimestamp - twapPeriod
            )
        ) {
            // set to earliest observation time if:
            // a) twap period is 0 (not set)
            // b) now - twap period is before earliest observation
            secondsArray[0] = earliestObservationSecondsAgo;
        } else {
            secondsArray[0] = twapPeriod;
        }
        secondsArray[1] = 0;
        (int56[] memory prices, ) = pool.observe(secondsArray);

        int128 twap = Utils.getTWAP(prices, secondsArray[0]);
        if (token1Decimals > token0Decimals) {
            // divide twap by token decimal difference
            twap = ABDKMath64x64.mul(
                twap,
                ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier)
            );
        } else if (token0Decimals > token1Decimals) {
            // multiply twap by token decimal difference
            int128 multiplierFixed =
                ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier);
            twap = ABDKMath64x64.mul(twap, multiplierFixed);
        }
        return twap;
    }
// Solidity 0.7.6
/**
 * Checks if twap deviates too much from the previous twap
 */
function checkTwap() private {
        int128 twap = getAsset0Price();
        int128 _lastTwap = lastTwap;
        int128 deviation =
            _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap;
        int128 maxDeviation =
            ABDKMath64x64.mul(
                twap,
                ABDKMath64x64.divu(1, maxTwapDeviationDivisor)
            );
        require(deviation <= maxDeviation, "Wrong twap");
        lastTwap = twap;
    }
// Solidity 0.5.15
// ========= ENTER ==========
function enter() public timeBoundsCheck {
        require(action == ACTION.ENTER, "Wrong action");
        require(!completed, "Action completed");
        uint256 ugasReserves;
        uint256 wethReserves;
        (wethReserves,ugasReserves, ) = uniswap_pair.getReserves();
        require(
            withinBounds(wethReserves, ugasReserves),
            "Market rate is outside bounds"
        );
        uint256 wethBalance = 300 * (10**18);
        // Since we are aiming for a CR of 4, we can mint with up to 80% of reserves
        // We mint slightly less so we can be sure there will be enough WETH
        uint256 collateral_amount = (wethBalance * 79) / 100;
        uint256 mint_amount = (collateral_amount * ugasReserves) /
            wethReserves /
            4;
        _mint(collateral_amount, mint_amount);

        _mintLPToken(uniswap_pair, WETH, UGAS, mint_amount, RESERVES);

        completed = true;
    }
// Solidity 0.5.15
// ========== EXIT  ==========
function exit() public timeBoundsCheck {
        require(action == ACTION.EXIT);
        require(!completed, "Action completed");
        uint256 ugasReserves;
        uint256 wethReserves;
        (wethReserves,ugasReserves, ) = uniswap_pair.getReserves();
        require(
            withinBounds(wethReserves, ugasReserves),
            "Market rate is outside bounds"
        );

        _burnLPToken(uniswap_pair, address(this));

        _repayAndWithdraw();

        WETH.transfer(RESERVES, WETH.balanceOf(address(this)));
        uint256 ugasBalance = UGAS.balanceOf(address(this));
        if (ugasBalance > 0) {
            UGAS.transfer(RESERVES, ugasBalance);
        }
        completed = true;
    }
// Solidity 0.5.6
// -------------------------------------------------------------------------------------------------------
// CANCELLATION FUNCTIONS --------------------------------------------------------------------------------
function calculateCancel(Booking storage booking)
    internal view returns (bool isPossible, uint depositToHostPpm, uint cleaningToHostPpm, uint priceToHostPpm) {

        // initialization
        isPossible = false;
        IBooking.Status currentStatus = getStatus(booking);

        (uint nightsAlreadyOccupied, uint nightsTotal) = getNights(booking);

        // checking
        if ((currentStatus != IBooking.Status.Booked && currentStatus != IBooking.Status.Started) ||
            (nightsTotal == 0 || nightsAlreadyOccupied >= nightsTotal) ||
            (currentStatus == IBooking.Status.Started && msg.sender == booking.host)) {
            return (false, 0, 0, 0);
        }

        depositToHostPpm = 0;
        cleaningToHostPpm = nightsAlreadyOccupied == 0 ? 0 : 1000000;
        priceToHostPpm = currentStatus == IBooking.Status.Booked && (msg.sender == booking.host || msg.sender == booking.feeBeneficiary)
            ? 0
            : getPriceToHostPpmByCancellationPolicy(booking, nightsAlreadyOccupied, nightsTotal, now);

        isPossible = true;
    }