lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.17
/**
 @notice Zap out in a single token
 @param _ToTokenContractAddress The ERC20 token to zapout in (address(0x00) if ether)
 @param _FromUniPoolAddress The uniswap pair address to zapout from
 @param _IncomingLP The amount of LP to remove.
 @param _minTokensRec indicates the minimum amount of tokens to receive
 @param _swapTarget indicates the execution target for swap.
 @param swap1Data DEX swap data
 @param swap2Data DEX swap data
 @param affiliate Affiliate address 
 @return the amount of eth/tokens received after zapout
 */
function ZapOut(
        address _ToTokenContractAddress,
        address _FromUniPoolAddress,
        uint256 _IncomingLP,
        uint256 _minTokensRec,
        address[] memory _swapTarget,
        bytes memory swap1Data,
        bytes memory swap2Data,
        address affiliate
    ) public nonReentrant stopInEmergency returns (uint256 tokenBought) {
        //transfer goodwill and reoves liquidity
        (uint256 amountA, uint256 amountB) = _removeLiquidity(
            _FromUniPoolAddress,
            _IncomingLP
        );

        //swaps tokens to token
        tokenBought = _swapTokens(
            _FromUniPoolAddress,
            amountA,
            amountB,
            _ToTokenContractAddress,
            _swapTarget,
            swap1Data,
            swap2Data
        );
        require(tokenBought >= _minTokensRec, "High slippage");

        emit zapOut(
            msg.sender,
            _FromUniPoolAddress,
            _ToTokenContractAddress,
            tokenBought
        );

        uint256 totalGoodwillPortion;

        // transfer toTokens to sender
        if (_ToTokenContractAddress == address(0)) {
            totalGoodwillPortion = _subtractGoodwill(
                ETHAddress,
                tokenBought,
                affiliate
            );

            msg.sender.transfer(tokenBought.sub(totalGoodwillPortion));
        } else {
            totalGoodwillPortion = _subtractGoodwill(
                _ToTokenContractAddress,
                tokenBought,
                affiliate
            );

            IERC20(_ToTokenContractAddress).safeTransfer(
                msg.sender,
                tokenBought.sub(totalGoodwillPortion)
            );
        }

        return tokenBought.sub(totalGoodwillPortion);
    }
// Solidity 0.5.17
/**
 @notice Zap out in a pair of tokens with permit
 @param _FromUniPoolAddress indicates the liquidity pool
 @param _IncomingLP indicates the amount of LP to remove from pool
 @param affiliate Affiliate address to share fees
 @param _permitData indicates the encoded permit data, which contains owner, spender, value, deadline, v,r,s values. 
 @return  amountA - indicates the amount received in token0, amountB - indicates the amount received in token1 
 */
function ZapOut2PairTokenWithPermit(
        address _FromUniPoolAddress,
        uint256 _IncomingLP,
        address affiliate,
        bytes calldata _permitData
    ) external stopInEmergency returns (uint256 amountA, uint256 amountB) {
        // permit
        (bool success, ) = _FromUniPoolAddress.call(_permitData);
        require(success, "Could Not Permit");

        (amountA, amountB) = ZapOut2PairToken(
            _FromUniPoolAddress,
            _IncomingLP,
            affiliate
        );
    }
// Solidity 0.5.17
/**
 @notice Zap out in a signle token with permit
 @param _ToTokenContractAddress indicates the toToken address to which tokens to convert.
 @param _FromUniPoolAddress indicates the liquidity pool
 @param _IncomingLP indicates the amount of LP to remove from pool
 @param _minTokensRec indicatest the minimum amount of toTokens to receive
 @param _permitData indicates the encoded permit data, which contains owner, spender, value, deadline, v,r,s values. 
 @param _swapTarget indicates the execution target for swap.
 @param swap1Data DEX swap data
 @param swap2Data DEX swap data
 @param affiliate Affiliate address to share fees
 */
function ZapOutWithPermit(
        address _ToTokenContractAddress,
        address _FromUniPoolAddress,
        uint256 _IncomingLP,
        uint256 _minTokensRec,
        bytes memory _permitData,
        address[] memory _swapTarget,
        bytes memory swap1Data,
        bytes memory swap2Data,
        address affiliate
    ) public stopInEmergency returns (uint256) {
        // permit
        (bool success, ) = _FromUniPoolAddress.call(_permitData);
        require(success, "Could Not Permit");

        return (
            ZapOut(
                _ToTokenContractAddress,
                _FromUniPoolAddress,
                _IncomingLP,
                _minTokensRec,
                _swapTarget,
                swap1Data,
                swap2Data,
                affiliate
            )
        );
    }
// Solidity 0.5.17
/**
 @notice this method returns the amount of tokens received in underlying tokens after removal of liquidity.
 @param _FromUniPoolAddress indicates the liquidity pool.
 @param _tokenA indicates the tokenA of pool
 @param _tokenB indicates the tokenB of pool
 @param _liquidity indicates the amount of liquidity to remove.
 @return  amountA - indicates the amount removed in token0, amountB - indicates the amount removed in token1 
 */
function removeLiquidityReturn(
        address _FromUniPoolAddress,
        address _tokenA,
        address _tokenB,
        uint256 _liquidity
    ) external view returns (uint256 amountA, uint256 amountB) {
        IUniswapV2Pair pair = IUniswapV2Pair(_FromUniPoolAddress);

        (uint256 amount0, uint256 amount1) = _getBurnAmount(
            _FromUniPoolAddress,
            pair,
            _tokenA,
            _tokenB,
            _liquidity
        );

        (address token0, ) = _sortTokens(_tokenA, _tokenB);

        (amountA, amountB) = _tokenA == token0
            ? (amount0, amount1)
            : (amount1, amount0);

        require(amountA >= 1, "UniswapV2Router: INSUFFICIENT_A_AMOUNT");
        require(amountB >= 1, "UniswapV2Router: INSUFFICIENT_B_AMOUNT");
    }
// Solidity 0.4.25
/**
 * @dev given a wolf token supply, reserve token balance, reserve ratio, and a deposit amount (in the reserve token),
 * calculates the return for a given conversion (in the wolf token)
 *
 * Formula:
 * Return = _supply * ((1 + _depositAmount / _reserveBalance) ^ (_reserveRatio / MAX_RESERVE_RATIO) - 1)
 *
 * @param _supply              wolf token total supply
 * @param _reserveBalance    total reserve token balance
 * @param _reserveRatio     reserve ratio, represented in ppm, 1-1000000
 * @param _depositAmount       deposit amount, in reserve token
 *
 *  @return purchase return amount
 */
function calculatePurchaseReturn(
        uint256 _supply,
        uint256 _reserveBalance,
        uint32 _reserveRatio,
        uint256 _depositAmount) public view returns (uint256)
    {
        // validate input
        require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO, "Invalid inputs.");
        // special case for 0 deposit amount
        if (_depositAmount == 0) {
            return 0;
        }
        // special case if the ratio = 100%
        if (_reserveRatio == MAX_RESERVE_RATIO) {
            return _supply.mul(_depositAmount).div(_reserveBalance);
        }
        uint256 result;
        uint8 precision;
        uint256 baseN = _depositAmount.add(_reserveBalance);
        (result, precision) = power(
            baseN, _reserveBalance, _reserveRatio, MAX_RESERVE_RATIO
        );
        uint256 newTokenSupply = _supply.mul(result) >> precision;
        return newTokenSupply.sub(_supply);
    }
// Solidity 0.4.25
/**
 * @dev given a wolf token supply, reserve token balance, reserve ratio and a sell amount (in the wolf token),
 * calculates the return for a given conversion (in the reserve token)
 *
 * Formula:
 * Return = _reserveBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_reserveRatio / MAX_RESERVE_RATIO)))
 *
 * @param _supply              wolf token total supply
 * @param _reserveBalance    total reserve token balance
 * @param _reserveRatio     constant reserve ratio, represented in ppm, 1-1000000
 * @param _sellAmount          sell amount, in the wolf token itself
 *
 * @return sale return amount
 */
function calculateSaleReturn(
        uint256 _supply,
        uint256 _reserveBalance,
        uint32 _reserveRatio,
        uint256 _sellAmount) public view returns (uint256)
    {
        // validate input
        require(_supply > 0 && _reserveBalance > 0 && _reserveRatio > 0 && _reserveRatio <= MAX_RESERVE_RATIO && _sellAmount <= _supply, "Invalid inputs.");
        // special case for 0 sell amount
        if (_sellAmount == 0) {
            return 0;
        }
        // special case for selling the entire supply
        if (_sellAmount == _supply) {
            return _reserveBalance;
        }
        // special case if the ratio = 100%
        if (_reserveRatio == MAX_RESERVE_RATIO) {
            return _reserveBalance.mul(_sellAmount).div(_supply);
        }
        uint256 result;
        uint8 precision;
        uint256 baseD = _supply.sub(_sellAmount);
        (result, precision) = power(
            _supply, baseD, MAX_RESERVE_RATIO, _reserveRatio
        );
        uint256 oldBalance = _reserveBalance.mul(result);
        uint256 newBalance = _reserveBalance << precision;
        return oldBalance.sub(newBalance).div(result);
    }
// Solidity 0.8.0
// Preminting 20 for marketing and community initatives
function _mintReservedTokens() internal onlyOwner {
      uint256 supply = totalSupply();
      uint256 _mintAmount = 20;
      require(supply == 0);
      
      for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(owner(), supply + i);
    }
  }
// Solidity 0.8.12
/* ------------- External ------------- */
function burnForBoost(IERC20 token) external payable {
        uint256 userData = _claimReward();

        uint256 boostCost = tokenBoostCosts[token];
        if (boostCost == 0) revert InvalidBoostToken();

        bool success = token.transferFrom(msg.sender, burnAddress, boostCost);
        if (!success) revert TransferFailed();

        uint256 boostStart = userData.boostStart();
        if (boostStart + TOKEN_BOOST_DURATION + TOKEN_BOOST_COOLDOWN > block.timestamp) revert BoostInEffect();

        _userData[msg.sender] = userData.setBoostStart(block.timestamp);

        emit BoostActivation(address(token));
    }
// Solidity 0.8.12
// calculates momentary totalBonus for display instead of effective bonus
function getUserStakeInfo(address user) external view returns (StakeInfo memory info) {
        unchecked {
            uint256 userData = _userData[user];

            info.numStaked = userData.numStaked();

            info.roleCount = userData.uniqueRoleCount();

            info.roleBonus = roleBonus(userData) / 100;
            info.specialGuestBonus = specialGuestBonus(user, userData) / 100;
            info.tokenBoost = (block.timestamp < userData.boostStart() + TOKEN_BOOST_DURATION) ? TOKEN_BONUS / 100 : 0;

            info.stakeStart = userData.stakeStart();
            info.timeBonus = (info.stakeStart > 0 &&
                block.timestamp > userData.stakeStart() + TIME_BONUS_STAKE_DURATION)
                ? TIME_BONUS / 100
                : 0;

            info.OGCount = userData.OGCount();
            info.OGBonus = (block.timestamp > OG_BONUS_END || userData.numStaked() == 0)
                ? 0
                : (userData.OGCount() * OG_BONUS) / userData.numStaked() / 100;

            info.rarityPoints = userData.rarityPoints();
            info.rarityBonus = rarityBonus(userData) / 100;

            info.totalBonus =
                info.roleBonus +
                info.specialGuestBonus +
                info.tokenBoost +
                info.timeBonus +
                info.rarityBonus +
                info.OGBonus;

            info.multiplierBase = userData.baseReward();
            info.dailyRewardBase = info.multiplierBase * dailyReward;

            info.dailyReward = (info.dailyRewardBase * (100 + info.totalBonus)) / 100;
            info.pendingReward = _pendingReward(user, userData);

            info.tokenBoostDelta = int256(TOKEN_BOOST_DURATION) - int256(block.timestamp - userData.boostStart());

            info.levelBalances = userData.levelBalances();
        }
    }
// Solidity 0.8.12
// O(N) read-only functions
function tokenIdsOf(address user, uint256 type_) external view returns (uint256[] memory) {
        unchecked {
            uint256 numTotal = type_ == 0 ? this.balanceOf(user) : type_ == 1
                ? this.numStaked(user)
                : this.numOwned(user);

            uint256[] memory ids = new uint256[](numTotal);

            if (numTotal == 0) return ids;

            uint256 count;
            for (uint256 i = startingIndex; i < totalSupply + startingIndex; ++i) {
                uint256 tokenData = _tokenDataOf(i);
                if (user == tokenData.trueOwner()) {
                    bool staked = tokenData.staked();
                    if ((type_ == 0 && !staked) || (type_ == 1 && staked) || type_ == 2) {
                        ids[count++] = i;
                        if (numTotal == count) return ids;
                    }
                }
            }

            return ids;
        }
    }
// Solidity 0.4.22
// low level token Pledge function
function procureTokens(address beneficiary) public payable {
    uint256 tokens;
    uint256 weiAmount = msg.value;
    uint256 backAmount;
    require(beneficiary != address(0));
    //minimum/maximum amount in ETH
    require(weiAmount >= minNumbPerSubscr && weiAmount <= maxNumbPerSubscr);
    if (now >= startICO && now <= endICO && totalICO < hardCap){
      tokens = weiAmount.mul(rate);
      if (hardCap.sub(totalICO) < tokens){
        tokens = hardCap.sub(totalICO); 
        weiAmount = tokens.div(rate);
        backAmount = msg.value.sub(weiAmount);
      }
      totalICO = totalICO.add(tokens);
    }

    require(tokens > 0);
    token.mint(beneficiary, tokens);
    balancesSoftCap[beneficiary] = balancesSoftCap[beneficiary].add(weiAmount);

    uint256 dateEndRefund = now + 14 * 1 days;
    paymentCounter[beneficiary] = paymentCounter[beneficiary] + 1;
    payments[beneficiary][paymentCounter[beneficiary]] = BuyInfo(weiAmount, tokens, dateEndRefund); 
    
    if (backAmount > 0){
      msg.sender.transfer(backAmount);  
    }
    emit TokenProcurement(msg.sender, beneficiary, weiAmount, tokens);
  }
// Solidity 0.8.12
// trait counts are set through hook in madmouse contract (MadMouse::_beforeStakeDataTransform)
function uniqueRoleCount(uint256 userData) internal pure returns (uint256) {
        unchecked {
            return (toUInt256((userData >> (128)) & 0xFF > 0) +
                toUInt256((userData >> (128 + 8)) & 0xFF > 0) +
                toUInt256((userData >> (128 + 16)) & 0xFF > 0) +
                toUInt256((userData >> (128 + 24)) & 0xFF > 0) +
                toUInt256((userData >> (128 + 32)) & 0xFF > 0));
        }
    }
// Solidity 0.8.12
// depends on the levels of the staked tokens (also set in hook MadMouse::_beforeStakeDataTransform)
// counts the base reward, depending on the levels of staked ids
function baseReward(uint256 userData) internal pure returns (uint256) {
        unchecked {
            return (((userData >> (168)) & 0xFF) +
                (((userData >> (168 + 8)) & 0xFF) << 1) +
                (((userData >> (168 + 16)) & 0xFF) << 2));
        }
    }
// Solidity 0.8.12
//  (should start at 128, 168; but role/level start at 1...)
function updateUserDataStake(uint256 userData, uint256 tokenData) internal pure returns (uint256) {
        unchecked {
            uint256 role = TokenDataOps.role(tokenData);
            if (role > 0) {
                userData += uint256(1) << (120 + (role << 3)); // roleBalances
                userData += TokenDataOps.rarity(tokenData) << 200; // rarityPoints
            }
            if (TokenDataOps.mintAndStake(tokenData)) userData += uint256(1) << 210; // OGCount
            userData += uint256(1) << (160 + (TokenDataOps.level(tokenData) << 3)); // levelBalances
            return userData;
        }
    }
// Solidity 0.8.12
// signatures will be created dynamically
function mint(
        uint256 amount,
        bytes calldata signature,
        bool stake
    ) external payable noContract {
        if (!publicSaleActive) revert PublicSaleNotActive();
        if (PURCHASE_LIMIT < amount) revert ExceedsLimit();
        if (msg.value != price * amount) revert IncorrectValue();
        if (!validSignature(signature, 0)) revert InvalidSignature();

        _mintAndStake(msg.sender, amount, stake);
    }
// Solidity 0.8.12
// update role, level information when staking
function _beforeStakeDataTransform(
        uint256 tokenId,
        uint256 userData,
        uint256 tokenData
    ) internal view override returns (uint256, uint256) {
        // assumption that mint&stake won't have revealed yet
        if (!tokenData.mintAndStake() && tokenData.role() == 0 && revealed)
            tokenData = tokenData.setRoleAndRarity(computeDNA(tokenId));
        userData = userData.updateUserDataStake(tokenData);
        return (userData, tokenData);
    }
// Solidity 0.8.12
// note: must be guarded by check for revealed
function updateDataWhileStaked(
        uint256 userData,
        uint256 tokenId,
        uint256 oldTokenData,
        uint256 newTokenData
    ) private view returns (uint256, uint256) {
        uint256 userDataX;
        // add in the role and rarity data if not already
        uint256 tokenDataX = newTokenData.role() != 0
            ? newTokenData
            : newTokenData.setRoleAndRarity(computeDNA(tokenId));

        // update userData as if to unstake with old tokenData and stake with new tokenData
        userDataX = userData.updateUserDataUnstake(oldTokenData).updateUserDataStake(tokenDataX);
        return applySafeDataTransform(userData, newTokenData, userDataX, tokenDataX);
    }
// Solidity 0.8.12
// simulates a token update and only returns ids != 0 if
// the user gets a bonus increase upon updating staked data
function shouldUpdateStakedIds(address user) external view returns (uint256[] memory) {
        if (!revealed) return new uint256[](0);

        uint256[] memory stakedIds = this.tokenIdsOf(user, 1);

        uint256 userData = _userData[user];
        uint256 oldTotalBonus = totalBonus(user, userData);

        uint256 tokenData;
        for (uint256 i; i < stakedIds.length; ++i) {
            tokenData = _tokenDataOf(stakedIds[i]);
            if (tokenData.role() == 0)
                (userData, ) = updateDataWhileStaked(userData, stakedIds[i], tokenData, tokenData);
            else stakedIds[i] = 0;
        }

        uint256 newTotalBonus = totalBonus(user, userData);

        return (newTotalBonus > oldTotalBonus) ? stakedIds : new uint256[](0);
    }
// Solidity 0.4.25
/**
 General Description:
 Determine a value of precision.
 Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision.
 Return the result along with the precision used.
 Detailed Description:
 Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)".
 The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision".
 The larger "precision" is, the more accurately this value represents the real value.
 However, the larger "precision" is, the more bits are required in order to store this value.
 And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x").
 This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)".
 Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function.
 This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations.
 This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul".
 */
function power(
        uint256 _baseN,
        uint256 _baseD,
        uint32 _expN,
        uint32 _expD
    ) internal view returns (uint256, uint8)
    {
        require(_baseN < MAX_NUM, "baseN exceeds max value.");
        require(_baseN >= _baseD, "Bases < 1 are not supported.");

        uint256 baseLog;
        uint256 base = _baseN * FIXED_1 / _baseD;
        if (base < OPT_LOG_MAX_VAL) {
            baseLog = optimalLog(base);
        } else {
            baseLog = generalLog(base);
        }

        uint256 baseLogTimesExp = baseLog * _expN / _expD;
        if (baseLogTimesExp < OPT_EXP_MAX_VAL) {
            return (optimalExp(baseLogTimesExp), MAX_PRECISION);
        } else {
            uint8 precision = findPositionInMaxExpArray(baseLogTimesExp);
            return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision);
        }
    }
// Solidity 0.4.25
/**
 Compute log(x / FIXED_1) * FIXED_1.
 This functions assumes that "x >= FIXED_1", because the output would be negative otherwise.
 */
function generalLog(uint256 _x) internal pure returns (uint256) {
        uint256 res = 0;
        uint256 x = _x;

        // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
        if (x >= FIXED_2) {
            uint8 count = floorLog2(x / FIXED_1);
            x >>= count; // now x < 2
            res = count * FIXED_1;
        }

        // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
        if (x > FIXED_1) {
            for (uint8 i = MAX_PRECISION; i > 0; --i) {
                x = (x * x) / FIXED_1; // now 1 < x < 4
                if (x >= FIXED_2) {
                    x >>= 1; // now 1 < x < 2
                    res += ONE << (i - 1);
                }
            }
        }

        return res * LN2_NUMERATOR / LN2_DENOMINATOR;
    }
// Solidity 0.4.25
/**
 Compute the largest integer smaller than or equal to the binary logarithm of the input.
 */
function floorLog2(uint256 _n) internal pure returns (uint8) {
        uint8 res = 0;
        uint256 n = _n;

        if (n < 256) {
            // At most 8 iterations
            while (n > 1) {
                n >>= 1;
                res += 1;
            }
        } else {
            // Exactly 8 iterations
            for (uint8 s = 128; s > 0; s >>= 1) {
                if (n >= (ONE << s)) {
                    n >>= s;
                    res |= s;
                }
            }
        }

        return res;
    }
// Solidity 0.4.25
/**
 The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent:
 - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"]
 - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"]
 */
function findPositionInMaxExpArray(uint256 _x)
    internal view returns (uint8)
    {
        uint8 lo = MIN_PRECISION;
        uint8 hi = MAX_PRECISION;

        while (lo + 1 < hi) {
            uint8 mid = (lo + hi) / 2;
            if (maxExpArray[mid] >= _x)
                lo = mid;
            else
                hi = mid;
        }

        if (maxExpArray[hi] >= _x)
            return hi;
        if (maxExpArray[lo] >= _x)
            return lo;

        assert(false);
        return 0;
    }