lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.0
/// @dev Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions.
function _performResolution(uint256 resNum) internal {
        if (resolutions[resNum].resType == resTypeAddOwner) {
            _addOwner(resolutions[resNum].newAddress);
        } else if (resolutions[resNum].resType == resTypeRemoveOwner) {
            _removeOwner(resolutions[resNum].oldAddress);
        } else if (resolutions[resNum].resType == resTypeReplaceOwner) {
            _replaceOwner(
                resolutions[resNum].oldAddress,
                resolutions[resNum].newAddress
            );
        } else if (resolutions[resNum].resType == resTypeAddOperator) {
            _addOperator(resolutions[resNum].newAddress);
        } else if (resolutions[resNum].resType == resTypeRemoveOperator) {
            _removeOperator(resolutions[resNum].oldAddress);
        } else if (resolutions[resNum].resType == resTypeReplaceOperator) {
            _replaceOperator(
                resolutions[resNum].oldAddress,
                resolutions[resNum].newAddress
            );
        } else if (
            resolutions[resNum].resType == resTypeUpdateTransactionLimit
        ) {
            _updateTransactionLimit(uint160(resolutions[resNum].newAddress));
        } else if (resolutions[resNum].resType == resTypeUpdateThreshold) {
            _updateThreshold(uint160(resolutions[resNum].newAddress));
        } else if (resolutions[resNum].resType == resTypePause) {
            _pause();
        } else if (resolutions[resNum].resType == resTypeUnpause) {
            _unpause();
        } else {
            _customResolutions(resNum);
            return;
        }

        resolutions[resNum].passed = true;
    }
// Solidity 0.6.12
// Seeds setup.
function rndSeeds(address[] calldata seeds, uint16[] calldata weis) public onlyOwner {
        require(rnds.length() == 0, "!rnds");
        require(seeds.length == weis.length, "!same length");

        uint256 sum = 0;
        uint256 len = seeds.length;
        for(uint256 i = 0; i < len; ++i) {
            if(weis[i] != 0 && seeds[i] != address(0)) {
                rnds.set(sum, seeds[i]);
                sum += weis[i];
                
                // setup referrer
                setReferrer(seeds[i], owner);
            }
        }
        
        // put an additional element as sentinel
        rnds.set(sum, owner);
        rndSeedMax = sum;
    }
// Solidity 0.6.6
// function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
//     address token,
//     uint liquidity,
//     uint amountTokenMin,
//     uint amountETHMin,
//     address to,
//     uint deadline,
//     bool approveMax, uint8 v, bytes32 r, bytes32 s
// ) external virtual override returns (uint amountETH) {
//     // address pair = ExcavoLibrary.pairFor(factory, token, WETH);
//     // uint value = approveMax ? uint(-1) : liquidity;
//     // IExcavoPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
//     // amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
//     //     token, liquidity, amountTokenMin, amountETHMin, to, deadline
//     // );
// }
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to, uint discount) internal virtual {
        for (uint i; i < path.length - 1; i++) {
            (address input, address output) = (path[i], path[i + 1]);
            (address token0,) = ExcavoLibrary.sortTokens(input, output);
            uint amountOut = amounts[i + 1];
            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
            address to = i < path.length - 2 ? ExcavoLibrary.pairFor(factory, output, path[i + 2]) : _to;
            
            IExcavoPair(ExcavoLibrary.pairFor(factory, input, output)).swap(
                amount0Out, amount1Out, to, new bytes(0), discount
            );
        }
    }
// Solidity 0.5.6
/**
 * @dev function to withdraw balance
 */
function withdraw(address customerAddress) internal {
    uint256 _dividends = dividendsOf(customerAddress);

    payoutsTo[customerAddress] += (int256) (_dividends);
    _dividends = _dividends.add(refBalance[customerAddress]);
    refBalance[customerAddress] = 0;

    if (_dividends > 0) {
      address payable _customerAddress = address(uint160(customerAddress));
      _customerAddress.transfer(_dividends);

      emit onWithdraw(customerAddress, _dividends);
    }
  }
// Solidity 0.5.6
/**
 * @dev function to reinvest of dividends
 */
function reinvest() onlyParticipant public {
    uint256 _dividends = showMyDividends(false);
    address _customerAddress = msg.sender;

    payoutsTo[_customerAddress] += (int256) (_dividends);
    _dividends = _dividends.add(refBalance[_customerAddress]);
    refBalance[_customerAddress] = 0;

    uint256 _tokens = buyTokens(_customerAddress, _dividends, address(0));

    emit onReinvestment(_customerAddress, _dividends, _tokens);
  }
// Solidity 0.5.6
/**
 * @dev function to show ether/tokens ratio
 * @param _eth eth amount
 */
function showEthToTokens(uint256 _eth) public view returns (uint256 _tokensReceived, uint256 _newTokenPrice) {
   uint256 b = actualTokenPrice.mul(2).sub(tokenPriceIncremental);
   uint256 c = _eth.mul(2);
   uint256 d = SafeMath.add(b**2, tokenPriceIncremental.mul(4).mul(c));

   // d = b**2 + 4 * a * c;
   // (-b + Math.sqrt(d)) / (2*a)
   _tokensReceived = SafeMath.div(sqrt(d).sub(b).mul(decimalShift), tokenPriceIncremental.mul(2));
   _newTokenPrice = actualTokenPrice.add(tokenPriceIncremental.mul(_tokensReceived).div(decimalShift));
 }
// Solidity 0.5.6
/**
 * @dev function to show tokens/ether ratio
 * @param _tokens tokens amount
 */
function showTokensToEth(uint256 _tokens) public view returns (uint256 _eth, uint256 _newTokenPrice) {
   // (2 * a1 - delta * (n - 1)) / 2 * n
   _eth = SafeMath.sub(actualTokenPrice.mul(2), tokenPriceIncremental.mul(_tokens.sub(1e18)).div(decimalShift)).div(2).mul(_tokens).div(decimalShift);
   _newTokenPrice = actualTokenPrice.sub(tokenPriceIncremental.mul(_tokens).div(decimalShift));
 }
// Solidity 0.5.6
/**
 * @dev function to buy tokens, calculate bonus, dividends, fees
 * @param _inRawEth eth amount
 * @param _ref address of referal
 */
function buyTokens(address customerAddress, uint256 _inRawEth, address _ref) internal returns (uint256) {
      uint256 _dividends = inBonus_p.mul(_inRawEth);
      uint256 _inEth = _inRawEth.sub(_dividends);
      uint256 _tokens = 0;
      uint256 startPrice = actualTokenPrice;

      if (_ref != address(0) && _ref != customerAddress && balanceOf(_ref) >= refMinBalanceReq) {
        uint256 _refBonus = refBonus_p.mul(_dividends);
        _dividends = _dividends.sub(_refBonus);
        refBalance[_ref] = refBalance[_ref].add(_refBonus);
      }

      uint256 _totalTokensSupply = totalSupply();

      if (_totalTokensSupply > 0) {
        _tokens = ethToTokens(_inEth);
        require(_tokens > 0);
        profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(_totalTokensSupply));
        _totalTokensSupply = _totalTokensSupply.add(_tokens);
      } else {
        // initial protect
        if (!isOwner()) {
            address(uint160(owner())).transfer(msg.value);
            return 0;
        }

        _totalTokensSupply = ethToTokens(_inRawEth);
        _tokens = _totalTokensSupply;
      }

      _mint(customerAddress, _tokens);
      payoutsTo[customerAddress] += (int256) (profitPerToken.mul(_tokens).div(decimalShift));

      emit onTokenBuy(customerAddress, _inEth, _tokens, _ref, now, startPrice, actualTokenPrice);

      return _tokens;
  }
// Solidity 0.5.6
/**
 * @dev function to sell tokens, calculate dividends, fees
 * @param _inRawTokens eth amount
 */
function sellTokens(uint256 _inRawTokens) internal returns (uint256) {
    address _customerAddress = msg.sender;
    require(_inRawTokens <= balanceOf(_customerAddress));
    uint256 _tokens = _inRawTokens;
    uint256 _eth = 0;
    uint256 startPrice = actualTokenPrice;

    _eth = tokensToEth(_tokens);
    _burn(_customerAddress, _tokens);

    uint256 _dividends = outBonus_p.mul(_eth);
    uint256 _ethTaxed = _eth.sub(_dividends);
    int256 unlockPayout = (int256) (_ethTaxed.add((profitPerToken.mul(_tokens)).div(decimalShift)));

    payoutsTo[_customerAddress] -= unlockPayout;
    profitPerToken = profitPerToken.add(_dividends.mul(decimalShift).div(totalSupply()));

    emit onTokenSell(_customerAddress, _tokens, _eth, now, startPrice, actualTokenPrice);
  }
// Solidity 0.8.9
/**
 * @notice Function to recover funds
 * Owner is assumed to be governance or AcknoLedger trusted party for helping users
 * @param token Address of token to be rescued
 * @param destination User address
 * @param amount Amount of tokens
 */
function recoverToken(
        address token,
        address destination,
        uint256 amount
    ) external onlyGovernance {
        require(token != destination, "Invalid address");
        require(destination != address(0), "Invalid address");
        require(IERC20(token).transfer(destination, amount), "Retrieve failed");
        emit RecoverToken(token, destination, amount);
    }
// Solidity 0.5.8
/// @notice given an amount of money returns how many tokens the money will result in with the
/// current round's pricing
function calculateTokenCount(uint money) public view returns (uint count, uint change) {
    require(isSaleOpen, "sale is no longer open and tokens can't be purchased");

    // get current token price
    uint price = _rounds[_currentRound].tokenPrice;
    uint capacityLeft = _rounds[_currentRound].capacityLeft;

    // money sent must be bigger than or equal the price, otherwise, no purchase is necessary
    if (money < price) {
      // return all the money
      return (0, money);
    }

    count = money / price;
    change = money % price;

    // Ensure there's sufficient capacity in the current round. If the user wishes to
    // purchase more, they can send money again to purchase tokens at the next round
    if (count > capacityLeft) {
      change += price * (count - capacityLeft);
      count = capacityLeft;
    }

    return (count, change);
  }
// Solidity 0.5.8
/// increases the round or closes the sale if tokens are sold out
function updateRounds(uint tokens) private {
    Round storage currentRound = _rounds[_currentRound];
    currentRound.capacityLeft -= tokens;

    if (currentRound.capacityLeft <= 0) {
      if (_currentRound == _rounds.length - 1) {
        isSaleOpen = false;
        emit SaleCompleted();
      } else {
        _currentRound++;
        emit RoundChanged(currentRound.tokenPrice, _rounds[_currentRound].tokenPrice);
      }
    }
  }
// Solidity 0.5.17
/**
 @dev Deposit funds into the contract. The caller must send (for Coin) or approve (for ERC20) value equal to or `denomination` of this instance.
 @param _commitment the note commitment, which is PedersenHash(nullifier + secret)
 */
function deposit(bytes32 _commitment) external payable nonReentrant {
    require(!commitments[_commitment], "The commitment has been submitted");
    require(msg.value >= coinDenomination, "insufficient coin amount");
    uint256 refund = msg.value - coinDenomination;
    uint32 insertedIndex = _insert(_commitment);
    commitments[_commitment] = true;
    updateBlockReward();
    uint256 cycDeno = cycDenomination();
    uint256 fee = anonymityFee;
    if (cycDeno.add(fee) > 0) {
      require(cycToken.transferFrom(msg.sender, address(this), cycDeno.add(fee)), "insufficient CYC allowance");
    }
    if (fee > 0) {
      address t = treasury;
      if (t == address(0)) {
        require(cycToken.burn(fee), "failed to burn anonymity fee");
      } else {
        safeTransfer(cycToken, t, fee);
      }
    }
    uint256 td = tokenDenomination;
    if (td > 0) {
      token.safeTransferFrom(msg.sender, address(this), td);
    }
    accumulateCYC += cycDeno;
    numOfShares += 1;
    if (refund > 0) {
      (bool success, ) = msg.sender.call.value(refund)("");
      require(success, "failed to refund");
    }
    emit Deposit(_commitment, insertedIndex, block.timestamp, cycDeno, fee);
  }
// Solidity 0.5.17
/** @dev whether an array of notes is already spent */
function isSpentArray(bytes32[] calldata _nullifierHashes) external view returns(bool[] memory spent) {
    spent = new bool[](_nullifierHashes.length);
    for(uint i = 0; i < _nullifierHashes.length; i++) {
      if (isSpent(_nullifierHashes[i])) {
        spent[i] = true;
      }
    }
  }
// Solidity 0.5.8
/// @notice casts a vote for a given choice
function cast(uint choice) public {
    require(choice < numChoices, "invalid choice to vote on");
    require(voters[msg.sender] == false, "you've already cast your vote, can't vote twice");

    address voter = msg.sender;
    uint256 weight = token.balanceOf(voter);

    require(weight > 0, "you don't own any tokens and therefore can't vote");
    require(weight > 1199, "you need to own at least 1200 shares to vote");

    // track the fact that vote has been cast
    voters[voter] = true;
    voteCount++;
    votes[choice] += weight;

    emit VoteCast(voter, choice, weight);
  }
// Solidity 0.8.12
/**
 	 * @notice min amount needed to become king
 	 * @param amount - how much you want to add
 	 * @param message - your kings message
 	 */
function claimThrone(uint256 amount, string memory message) external whenNotPaused nonReentrant {
		require(amount >= minAmountNeeded(), "check minAmountNeeded()");

		uint256 comission = _calcPercentage(amount, 100);
		tuna.transferFrom(msg.sender, address(this), comission);
		tuna.transferFrom(msg.sender, king, amount - comission);

		currentKingAmount = amount;
		king = msg.sender;
		kingMessage = message;
	}
// Solidity 0.4.11
/* Transfer function when _to represents a contract address, with the caveat
 that the contract needs to implement the tokenFallback function in order to receive tokens */
function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) {
        balances[msg.sender] -= _value;
        balances[_to] += _value;
        ContractReceiver receiver = ContractReceiver(_to);
        receiver.tokenFallback(msg.sender, _value, _data);
        Transfer(msg.sender, _to, _value);
        Transfer(msg.sender, _to, _value, _data);
        return true;
    }
// Solidity 0.4.11
/* Infers if whether _address is a contract based on the presence of bytecode */
function isContract(address _address) internal returns (bool is_contract) {
        uint length;
        if (_address == 0) return false;
        assembly {
            length := extcodesize(_address)
        }
        if(length > 0) {
            return true;
        } else {
            return false;
        }
    }
// Solidity 0.4.11
/* Remove the specified amount of the tokens from the supply permanently */
function burn(uint256 _value, bytes _data) returns (bool success) {
        if (balances[msg.sender] >= _value
            && _value > 0) {
            balances[msg.sender] -= _value;
            _currentSupply -= _value;
            Burn(msg.sender, _value, _currentSupply, _data);
            return true;
        } else {
            return false;
        }
    }
// Solidity 0.5.10
//Generate random number between 1 & max
function rand(uint max, uint256 seed) private returns (uint256 result){
        
        uint256 factor = seed * 100 / max;
        uint256 lastBlockNumber = block.number - 1;
        uint256 hashVal = uint256(blockhash(lastBlockNumber));
        return (uint256((uint256(hashVal) / factor)) % max) + 1;
    }
// Solidity 0.7.6
/**
 *   @notice This function returns base,ask and bid range ticks for the given pool
 *   - It fetches the current tick and tick spacing of the pool
 *   - Multiples the tick spacing with pools base and range multipliers
 *   - Calculates pools twap and verifies whether it is under the maxtwapdeviation
 *   - If the price is under the deviation limit, it returns the base ranges along with range order ticks
 *   @param _pool: pool address
 **/
function getTicks(address _pool)
        external
        override
        onlyExchange
        returns (
            int24 baseLower,
            int24 baseUpper,
            int24 bidLower,
            int24 bidUpper,
            int24 askLower,
            int24 askUpper
        )
    {
        (int24 tick, int24 tickSpacing) = getCurrentTick(_pool);

        if (poolStrategy[_pool].baseThreshold == 0) {
            int24 baseFloor = _floor(baseTicks, tickSpacing);

            poolStrategy[_pool] = PoolStrategy({
                baseThreshold: baseFloor,
                rangeThreshold: _floor(rangeTicks, tickSpacing),
                maxTwapDeviation: maxTwapDeviation,
                readjustThreshold: (baseFloor * readjustMultiplier) / 100,
                twapDuration: twapDuration
            });
        }
        rangeOrder = poolStrategy[_pool].rangeThreshold;

        int24 maxThreshold = poolStrategy[_pool].baseThreshold > rangeOrder
            ? poolStrategy[_pool].baseThreshold
            : rangeOrder;

        require(
            (tick > TickMath.MIN_TICK + maxThreshold + tickSpacing) &&
                (tick < (TickMath.MAX_TICK - maxThreshold - tickSpacing)),
            "IT"
        );
        int24 twap = calculateTwap(_pool);
        int24 deviation = tick > twap ? tick - twap : twap - tick;

        require(deviation <= poolStrategy[_pool].maxTwapDeviation, "MTF");

        int24 tickFloor = _floor(tick, tickSpacing);
        int24 tickCeil = tickFloor + tickSpacing;

        baseLower = tickFloor - poolStrategy[_pool].baseThreshold;
        baseUpper = tickFloor + poolStrategy[_pool].baseThreshold;
        bidLower = tickFloor - rangeOrder;
        bidUpper = tickFloor;
        askLower = tickCeil;
        askUpper = tickCeil + rangeOrder;
    }
// Solidity 0.7.6
/**
 *   @notice This function updates the range,base threshold and twap values specific to a pool
 *   @param params: struct values of PoolStrategy struct, the values can be inspected from interface
 *   @param _pool<: pool address
 **/
function changeStrategy(PoolStrategy memory params, address _pool)
        public
        onlyGovernance
    {
        PoolStrategy memory oldStrategy = poolStrategy[_pool];
        validateStrategy(params.baseThreshold, IUniswapV3Pool(_pool).tickSpacing());
        emit StrategyUpdated(
            oldStrategy,
            poolStrategy[_pool] = PoolStrategy({
                baseThreshold: params.baseThreshold,
                rangeThreshold: params.rangeThreshold,
                maxTwapDeviation: params.maxTwapDeviation,
                readjustThreshold: params.readjustThreshold,
                twapDuration: params.twapDuration
            })
        );
    }
// Solidity 0.7.6
/**
 *   @notice This function calculates the current twap of pool
 *   @param pool: pool address
 **/
function calculateTwap(address pool) internal view returns (int24 twap) {
        uint128 inRangeLiquidity = IUniswapV3Pool(pool).liquidity();
        if (inRangeLiquidity == 0) {
            (uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
            twap = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
        } else {
            twap = getTwap(pool);
        }
    }
// Solidity 0.7.6
/**
 *   @notice This function fetches the twap of pool from the observation
 *   @param _pool: pool address
 **/
function getTwap(address _pool) public view override returns (int24 twap) {
        IUniswapV3Pool uniswapV3Pool = IUniswapV3Pool(_pool);
        (, , uint16 observationIndex, uint16 observationCardinality, , , ) = uniswapV3Pool
            .slot0();
        (uint32 lastTimeStamp, , , ) = uniswapV3Pool.observations(
            (observationIndex + 1) % observationCardinality
        );
        uint32 timeDiff = uint32(block.timestamp) - lastTimeStamp;
        uint32 duration = poolStrategy[_pool].twapDuration;
        if (duration == 0) {
            duration = twapDuration;
        }
        twap = OracleLibrary.consult(_pool, timeDiff > duration ? duration : timeDiff);
    }
// Solidity 0.7.6
/**
 *   @notice This function calculates the lower tick value from the current tick
 *   @param tick: current tick of the pool
 *   @param tickSpacing: tick spacing according to the fee tier
 **/
function _floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
        int24 compressed = tick / tickSpacing;
        if (tick < 0 && tick % tickSpacing != 0) compressed--;
        return compressed * tickSpacing;
    }
// Solidity 0.5.10
//at least min_amount blocks to call this
function earnReward(uint min_amount) public onlyOwner{
    require(block.number.safeSub(last_earn_block) >= earn_gap, "not long enough");
    last_earn_block = block.number;

    uint256 index = get_pid(ICurvePool(current_pool).get_lp_token_addr());
    (,,,address crvRewards,,) = convex_booster.poolInfo(index);
    ConvexRewardInterface(crvRewards).getReward(address(this), true);

    for(uint i = 0; i < extra_yield_tokens.length; i++){
      uint256 amount = IERC20(extra_yield_tokens[i]).balanceOf(address(this));
      if(amount > 0){
        require(yield_handler != YieldHandlerInterface(0x0), "invalid yield handler");
        IERC20(extra_yield_tokens[i]).approve(address(yield_handler), amount);
        if(target_token == address(0x0)){
          yield_handler.handleExtraToken(extra_yield_tokens[i], weth, amount, min_amount);
        }else{
          yield_handler.handleExtraToken(extra_yield_tokens[i], target_token, amount, min_amount);
        }
      }
    }

    uint256 amount = TransferableToken.balanceOfAddr(target_token, address(this));
    _refundTarget(amount);
  }
// Solidity 0.4.21
/// @notice Transfer "_value" tokens from "_from" to "_to" if "msg.sender" is allowed.
/// @dev Allows for an approved third party to transfer tokens from one
/// address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
/// @return Returns success of function call.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
    {
        //Address shouldn't be null
        require(_from != 0x0);
        require(_to != 0x0);
        require(_to != address(this));
        require(balances[_from] >= _value);
        require(allowed[_from][msg.sender] >= _value);
        require(balances[_to] + _value >= balances[_to]);

        balances[_to] += _value;
        balances[_from] -= _value;
        allowed[_from][msg.sender] -= _value;

        emit Transfer(_from, _to, _value);

        return true;
    }
// Solidity 0.4.21
/// @notice Approves "_who" to transfer "_value" tokens from "msg.sender" to any address.
/// @dev Sets approved amount of tokens for the spender. Returns success.
/// @param _who Address of allowed account.
/// @param _value Number of approved tokens.
/// @return Returns success of function call.
function approve(address _who, uint256 _value) public returns (bool) {

        // Address shouldn't be null
        require(_who != 0x0);

        // To change the approve amount you first have to reduce the addresses`
        // allowance to zero by calling `approve(_who, 0)` if it is not
        // already 0 to mitigate the race condition described here:
        // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
        require(_value == 0 || allowed[msg.sender][_who] == 0);

        allowed[msg.sender][_who] = _value;
        emit Approval(msg.sender, _who, _value);
        return true;
    }