lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.12
/**
 @notice This function is used swap tokens using multiple exchanges
 @param fromToken token addresses to swap from
 	@param toToken token addresses to swap into
 	@param amountIn amount of tokens to swap
 @param withPool indicates the exchange we want to swap from
 @param poolData pool or token addresses needed for swapping tokens according to the exchange
 	@return amount of tokens received after swap
 */
function _swapFromPool(
        address fromToken,
        address toToken,
        uint256 amountIn,
        uint256 withPool,
        address[] memory poolData
    ) internal returns (uint256) {
        require(fromToken != toToken, "Cannot swap same tokens");
        require(withPool <= 3, "Invalid Exchange");

        if (withPool == 1) {
            return
                _swapWithBalancer(poolData[0], fromToken, toToken, amountIn, 1);
        } else if (withPool == 2) {
            return
                _swapWithUniswapV2(fromToken, toToken, poolData, amountIn, 1);
        } else if (withPool == 3) {
            return _swapWithCurve(poolData[0], fromToken, toToken, amountIn, 1);
        }
    }
// Solidity 0.5.12
/**
 	@notice This function returns part of the given array 
 @param addresses address array to copy from
 	@param _start start index
 	@param _end end index
 @return addressArray copied from given array
 		 */
function _getPath(
        address[] memory addresses,
        uint256 _start,
        uint256 _end
    ) internal pure returns (address[] memory addressArray) {
        uint256 len = _end.sub(_start);
        require(len > 1, "ERR_UNIV2_PATH");
        addressArray = new address[](len);

        for (uint256 i = 0; i < len; i++) {
            if (
                addresses[_start + i] == address(0) ||
                addresses[_start + i] == ETHAddress
            ) {
                addressArray[i] = address(wethContract);
            } else {
                addressArray[i] = addresses[_start + i];
            }
        }
    }
// Solidity 0.4.18
// low level token purchase function
// @notice buyTokens
// @param beneficiary The address of the beneficiary
// @return the transaction address and send the event as TokenPurchase
function buyTokens(address beneficiary) public payable {
      require(publicSaleCap > 0);
      require(validPurchase());
      uint256  weiAmount = msg.value;
       
       // calculate token amount to be created
    uint256 tokens = weiAmount.mul(rate);

    uint256 Bonus = tokens.mul(getTimebasedBonusRate()).div(100);

    tokens = tokens.add(Bonus);
    
    if (state == State.PRESALE) {
        assert (soldTokenInPresale + tokens <= presaleCap);
        soldTokenInPresale = soldTokenInPresale.add(tokens);
        presaleCap=presaleCap.sub(tokens);
    } else if(state==State.PUBLICSALE){
         assert (soldTokenInPublicsale + tokens <= publicSaleCap);
        soldTokenInPublicsale = soldTokenInPublicsale.add(tokens);
        publicSaleCap=publicSaleCap.sub(tokens);
    }
       
       if(investedAmountOf[beneficiary] == 0) {
           // A new investor
           investorCount++;
        }
        // Update investor
        investedAmountOf[beneficiary] = investedAmountOf[beneficiary].add(weiAmount);
       forwardFunds();
       weiRaised = weiRaised.add(weiAmount);
       token.mint(beneficiary, tokens);
       TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
    
     }
// Solidity 0.4.25
/**
 * @dev Returns the rate of tokens per wei at the present time.
 * Note that, as price _increases_ with time, the rate _decreases_.
 * @return The number of tokens a buyer gets per wei at a given time
 */
function getCurrentRate() public view returns (uint256) {
        if (block.timestamp < 1528156799) {         // 4th of June 2018 23:59:59 GTC
            return 1050;
        } else if (block.timestamp < 1528718400) {  // 11th of June 2018 12:00:00 GTC
            return 940;
        } else if (block.timestamp < 1529323200) {  // 18th of June 2018 12:00:00 GTC
            return 865;
        } else if (block.timestamp < 1529928000) {  // 25th of June 2018 12:00:00 GTC
            return 790;
        } else {
            return 750;
        }
    }
// Solidity 0.4.18
// Get the time-based bonus rate
function getTimebasedBonusRate() internal constant returns (uint256) {
  	  uint256 bonusRate = 0;
      if (state == State.PRESALE) {
          bonusRate = 100;
      } else {
          uint256 nowTime = getNow();
          uint256 bonusFirstWeek = startTime + (7 days * 1000);
          uint256 bonusSecondWeek = bonusFirstWeek + (7 days * 1000);
          uint256 bonusThirdWeek = bonusSecondWeek + (7 days * 1000);
          uint256 bonusFourthWeek = bonusThirdWeek + (7 days * 1000);
          if (nowTime <= bonusFirstWeek) {
              bonusRate = 30;
          } else if (nowTime <= bonusSecondWeek) {
              bonusRate = 30;
          } else if (nowTime <= bonusThirdWeek) {
              bonusRate = 15;
          } else if (nowTime <= bonusFourthWeek) {
              bonusRate = 15;
          }
      }
      return bonusRate;
   }
// Solidity 0.8.7
// Staking CHAD APE
function stakeChadApe(uint256 tokenId) public {
        require(!paused, "Contract paused");
        require (msg.sender == CAGC.ownerOf(tokenId), "Sender must be the owner");
        require(CAGC.isApprovedForAll(msg.sender, address(this)));

        Staking memory staking = Staking(block.timestamp, msg.sender);
        stakings[tokenId] = staking;
        stakingsByOwner[msg.sender].push(tokenId);
        CAGC.transferFrom(msg.sender, address(this), tokenId);
    }
// Solidity 0.8.7
// Un-staking
function unstakeChadApe(uint256 tokenId) internal {
        Staking storage staking = stakings[tokenId];
        uint256[] storage stakedApes = stakingsByOwner[msg.sender];
        uint16 index = 0;
        for (; index < stakedApes.length; index++) {
            if (stakedApes[index] == tokenId) {
                break;
            }
        }
        require(index < stakedApes.length, "Chad Ape not found");
        stakedApes[index] = stakedApes[stakedApes.length - 1];
        stakedApes.pop();
        staking.owner = address(0);
        CAGC.transferFrom(address(this), msg.sender, tokenId);
    }
// Solidity 0.8.7
// emergency Un-staking
// remember user won't receive any rewards if the user use this method
function emergencyUnstakeChadApe(uint256 tokenId) external {
        require(CAGC.ownerOf(tokenId) == address(this), "The Chad Ape must be staked");
        Staking storage staking = stakings[tokenId];
        require(staking.owner == msg.sender, "Sender must be the owner");
        uint256[] storage stakedApes = stakingsByOwner[msg.sender];
        uint16 index = 0;
        for (; index < stakedApes.length; index++) {
            if (stakedApes[index] == tokenId) {
                break;
            }
        }
        require(index < stakedApes.length, "Chad Ape not found");
        stakedApes[index] = stakedApes[stakedApes.length - 1];
        stakedApes.pop();
        staking.owner = address(0);
        CAGC.transferFrom(address(this), msg.sender, tokenId);
    }
// Solidity 0.8.7
// Get staking info by user
function stakingInfo(address owner) public view returns (StakingInfo[] memory) {
        uint256 balance = stakedBalanceOf(owner);
        StakingInfo[] memory list = new StakingInfo[](balance);

        for (uint16 i = 0; i < balance; i++) {
            uint256 tokenId = stakingsByOwner[owner][i];
            Staking memory staking = stakings[tokenId];
            uint256 reward = calculateReward(tokenId);
            list[i] = StakingInfo(tokenId, staking.timestamp, reward);
        }

        return list;
    }
// Solidity 0.8.4
/**
 * @dev Deploys a contract using `CREATE2`. The address where the contract
 * will be deployed can be known in advance via {computeAddress}.
 *
 * The bytecode for a contract can be obtained from Solidity with
 * `type(contractName).creationCode`.
 *
 * Requirements:
 *
 * - `bytecode` must not be empty.
 * - `salt` must have not been used for `bytecode` already.
 * - the factory must have a balance of at least `amount`.
 * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
 */
function deploy(
        uint256 amount,
        bytes32 salt,
        bytes memory bytecode
    ) internal returns (address) {
        address addr;
        require(address(this).balance >= amount, "Create2: insufficient balance");
        require(bytecode.length != 0, "Create2: bytecode length is zero");
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        require(addr != address(0), "Create2: Failed on deploy");
        return addr;
    }
// Solidity 0.7.6
/// Can only be called by DrainController
function drain(uint256 pid) external {
        require(drainController == msg.sender, "not drainctrl");
        PoolInfo storage pool = poolInfo[pid];
        Victim victim = pool.victim;
        uint256 victimPoolId = pool.victimPoolId;
        victim.claimReward(pid, victimPoolId);
        IERC20 rewardToken = victim.rewardToken(pid);
        uint256 claimedReward = rewardToken.balanceOf(address(this));

        if (claimedReward == 0) {
            return;
        }

        uint256 wethReward = victim.sellRewardForWeth(pid, claimedReward, address(this));
        // Take a % of the drained reward to be redistributed to other contracts
        uint256 wethDrainAmount = wethReward.mul(wethDrainModifier).div(1000);
        if (wethDrainAmount > 0) {
            weth.transfer(drainAddress, wethDrainAmount);
            wethReward = wethReward.sub(wethDrainAmount);
        }

        // Remainder of rewards go to users of the drained pool as interest-bearing ETH
        uint256 ibethBefore = IIBVEth(IBVETH).balance(address(this));
        (bool success,) = IBVETH.delegatecall(abi.encodeWithSignature("handleDrainedWETH(uint256)", wethReward));
        require(success, "handleDrainedWETH(uint256 amount) delegatecall failed.");
        uint256 ibethAfter = IIBVEth(IBVETH).balance(address(this));

        pool.wethAccumulator = pool.wethAccumulator.add(ibethAfter.sub(ibethBefore));
    }
// Solidity 0.7.6
/// This function allows owner to take unsupported tokens out of the contract.
/// It also allows for removal of airdropped tokens.
function recoverUnsupported(IERC20 token, uint256 amount, address to) external onlyOwner {
        uint256 length = poolInfo.length;
        for (uint256 pid = 0; pid < length; ++pid) {
            PoolInfo storage pool = poolInfo[pid];
            IERC20 lpToken = pool.victim.lockableToken(pool.victimPoolId);
            // cant take staked asset
            require(token != lpToken, "!pool.lpToken");
        }
        // transfer to
        token.safeTransfer(to, amount);
    }
// Solidity 0.7.6
/// Claim rewards from pool
function _claim(uint256 pid, bool withdrawing, uint8 flag) internal {
        PoolInfo storage pool = poolInfo[pid];
        UserInfo storage user = userInfo[pid][msg.sender];
        uint256 pending = user.amount.mul(pool.accWethPerShare).div(1e12).sub(user.rewardDebt);
        if (pending > 0) {
            if (withdrawing && withdrawalPenalty > 0 && block.timestamp < user.coolOffTime) {
                uint256 fee = pending.mul(withdrawalPenalty).div(1000);
                pending = pending.sub(fee);
                pool.wethAccumulator = pool.wethAccumulator.add(fee);
            }

            (bool success,) = address(IBVETH).delegatecall(abi.encodeWithSignature("handleClaim(uint256,uint8)", pending, flag));
            require(success, "handleClaim(uint256 pending, uint8 flag) delegatecall failed.");
        }
    }
// Solidity 0.8.9
/// Hook that when enabled manually calls _beforeTokenTransfer on
function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal override {
        if (advancedConfig.hasTransferHook) {
            (bool success, ) = address(this).delegatecall(
                abi.encodeWithSignature(
                    "_beforeTokenTransfer(address,address,uint256)",
                    from,
                    to,
                    tokenId
                )
            );
            // Raise error again from result if error exists
            assembly {
                switch success
                // delegatecall returns 0 on error.
                case 0 {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
            }
        }
    }
// Solidity 0.8.9
/// Get royalty information for token
/// ignored token id to get royalty info. able to override and set per-token royalties
/// @param _salePrice sales price for token to determine royalty split
function royaltyInfo(uint256, uint256 _salePrice)
        external
        view
        override
        returns (address receiver, uint256 royaltyAmount)
    {
        // If ownership is revoked, don't set royalties.
        if (owner() == address(0x0)) {
            return (owner(), 0);
        }
        return (owner(), (_salePrice * advancedConfig.royaltyBps) / 10_000);
    }
// Solidity 0.6.11
/**
 * ERC2612 `permit`: 712-signed token approvals
 */
function permit(address holder, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
        require(deadline >= block.timestamp, 'MYST: Permit expired');
        bytes32 digest = keccak256(
            abi.encodePacked(
                '\x19\x01',
                DOMAIN_SEPARATOR,
                keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, value, nonces[holder]++, deadline))
            )
        );
        address recoveredAddress = ecrecover(digest, v, r, s);
        require(recoveredAddress != address(0) && recoveredAddress == holder, 'MYST: invalid signature');
        _approve(holder, spender, value);
    }
// Solidity 0.6.11
/**
 * Note that we're not decreasing allowance of uint(-1). This makes it simple to ERC777 operator.
 */
function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {
        // require(recipient != address(0), "MYST: transfer to the zero address");
        require(holder != address(0), "MYST: transfer from the zero address");
        address spender = _msgSender();

        // Allowance for uint256(-1) means "always allowed" and is analog for erc777 operators but in erc20 semantics.
        if (holder != spender && _allowances[holder][spender] != uint256(-1)) {
            _approve(holder, spender, _allowances[holder][spender].sub(amount, "MYST: transfer amount exceeds allowance"));
        }

        _move(holder, recipient, amount);
        return true;
    }
// Solidity 0.6.11
/**
 * Creates `amount` tokens and assigns them to `holder`, increasing
 * the total supply.
 */
function _mint(address holder, uint256 amount) internal {
        require(holder != address(0), "MYST: mint to the zero address");

        // Update state variables
        _totalSupply = _totalSupply.add(amount);
        _balances[holder] = _balances[holder].add(amount);

        emit Minted(holder, amount);
        emit Transfer(address(0), holder, amount);
    }
// Solidity 0.6.11
/**
 * Tokens can be upgraded by calling this function.
 */
function upgrade(uint256 amount) public {
        UpgradeState state = getUpgradeState();
        require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading, "MYST: token is not in upgrading state");

        require(amount != 0, "MYST: upgradable amount should be more than 0");

        address holder = _msgSender();

        // Burn tokens to be upgraded
        _burn(holder, amount);

        // Remember how many tokens we have upgraded
        _totalUpgraded = _totalUpgraded.add(amount);

        // Upgrade agent upgrades/reissues tokens
        _upgradeAgent.upgradeFrom(holder, amount);
        emit Upgrade(holder, upgradeAgent(), amount);
    }
// Solidity 0.6.11
/**
 * Setting new destination of funds recovery.
 */
function setFundsDestination(address newDestination) public {
        require(_msgSender()== _upgradeMaster, "MYST: only a master can set funds destination");
        require(newDestination != address(0), "MYST: funds destination can't be zero addreess");

        _fundsDestination = newDestination;
        emit FundsRecoveryDestinationChanged(_fundsDestination, newDestination);
    }
// Solidity 0.8.9
/**
 * @notice Add liquidity to the bridge pool. Pulls l1Token from the caller's wallet. The caller is sent back a
 * commensurate number of LP tokens (minted to their address) at the prevailing exchange rate.
 * @dev The caller must approve this contract to transfer `l1TokenAmount` amount of l1Token if depositing ERC20.
 * @dev The caller can deposit ETH which is auto wrapped to WETH. This can only be done if: a) this is the Weth pool
 * and b) the l1TokenAmount matches to the transaction msg.value.
 * @dev Reentrancy guard not added to this function because this indirectly calls sync() which is guarded.
 * @param l1TokenAmount Number of l1Token to add as liquidity.
 */
function addLiquidity(uint256 l1TokenAmount) public payable nonReentrant() {
        // If this is the weth pool and the caller sends msg.value then the msg.value must match the l1TokenAmount.
        // Else, msg.value must be set to 0.
        require((isWethPool && msg.value == l1TokenAmount) || msg.value == 0, "Bad add liquidity Eth value");

        // Since `exchangeRateCurrent()` reads this contract's balance and updates contract state using it,
        // we must call it first before transferring any tokens to this contract.
        uint256 lpTokensToMint = (l1TokenAmount * 1e18) / _exchangeRateCurrent();
        _mint(msg.sender, lpTokensToMint);
        liquidReserves += l1TokenAmount;

        if (msg.value > 0 && isWethPool) WETH9Like(address(l1Token)).deposit{ value: msg.value }();
        else l1Token.safeTransferFrom(msg.sender, address(this), l1TokenAmount);

        emit LiquidityAdded(l1TokenAmount, lpTokensToMint, msg.sender);
    }
// Solidity 0.8.9
/**
 * @notice Removes liquidity from the bridge pool. Burns lpTokenAmount LP tokens from the caller's wallet. The caller
 * is sent back a commensurate number of l1Tokens at the prevailing exchange rate.
 * @dev The caller does not need to approve the spending of LP tokens as this method directly uses the burn logic.
 * @dev Reentrancy guard not added to this function because this indirectly calls sync() which is guarded.
 * @param lpTokenAmount Number of lpTokens to redeem for underlying.
 * @param sendEth Enable the liquidity provider to remove liquidity in ETH, if this is the WETH pool.
 */
function removeLiquidity(uint256 lpTokenAmount, bool sendEth) public nonReentrant() {
        // Can only send eth on withdrawing liquidity iff this is the WETH pool.
        require(!sendEth || isWethPool, "Cant send eth");
        uint256 l1TokensToReturn = (lpTokenAmount * _exchangeRateCurrent()) / 1e18;

        // Check that there is enough liquid reserves to withdraw the requested amount.
        require(liquidReserves >= (pendingReserves + l1TokensToReturn), "Utilization too high to remove");

        _burn(msg.sender, lpTokenAmount);
        liquidReserves -= l1TokensToReturn;

        if (sendEth) _unwrapWETHTo(payable(msg.sender), l1TokensToReturn);
        else l1Token.safeTransfer(msg.sender, l1TokensToReturn);

        emit LiquidityRemoved(l1TokensToReturn, lpTokenAmount, msg.sender);
    }
// Solidity 0.8.9
/**
 * @notice Called by Disputer to dispute an ongoing relay.
 * @dev The result of this method is to always throw out the relay, providing an opportunity for another relay for
 * the same deposit. Between the disputer and proposer, whoever is incorrect loses their bond. Whoever is correct
 * gets it back + a payout.
 * @dev Caller must have approved this contract to spend the total bond + amount - fees for `l1Token`.
 * @param depositData the deposit data struct containing all the user's deposit information.
 * @param relayData RelayData logged in the disputed relay.
 */
function disputeRelay(DepositData memory depositData, RelayData memory relayData) public nonReentrant() {
        require(relayData.priceRequestTime + optimisticOracleLiveness > getCurrentTime(), "Past liveness");
        require(relayData.relayState == RelayState.Pending, "Not disputable");
        // Validate the input data.
        bytes32 depositHash = _getDepositHash(depositData);
        _validateRelayDataHash(depositHash, relayData);

        // Submit the proposal and dispute to the OO.
        bytes32 relayHash = _getRelayHash(depositData, relayData);

        // Note: in some cases this will fail due to changes in the OO and the method will refund the relayer.
        bool success =
            _requestProposeDispute(
                relayData.slowRelayer,
                msg.sender,
                relayData.proposerBond,
                relayData.finalFee,
                _getRelayAncillaryData(relayHash)
            );

        // Drop the relay and remove the bond from the tracked bonds.
        bonds -= relayData.finalFee + relayData.proposerBond;
        pendingReserves -= depositData.amount;
        delete relays[depositHash];
        if (success) emit RelayDisputed(depositHash, _getRelayDataHash(relayData), msg.sender);
        else emit RelayCanceled(depositHash, _getRelayDataHash(relayData), msg.sender);
    }
// Solidity 0.8.9
// Return hash of unique instant relay and deposit event. This is stored in state and mapped to a deposit hash.
function _getInstantRelayHash(bytes32 depositHash, RelayData memory relayData) private pure returns (bytes32) {
        // Only include parameters that affect the "correctness" of an instant relay. For example, the realized LP fee
        // % directly affects how many tokens the instant relayer needs to send to the user, whereas the address of the
        // instant relayer does not matter for determining whether an instant relay is "correct".
        return keccak256(abi.encode(depositHash, relayData.realizedLpFeePct));
    }
// Solidity 0.8.9
// Update internal fee counters by adding in any accumulated fees from the last time this logic was called.
function _updateAccumulatedLpFees() internal {
        // Calculate the unallocatedAccumulatedFees from the last time the contract was called.
        uint256 unallocatedAccumulatedFees = _getAccumulatedFees();

        // Decrement the undistributedLpFees by the amount of accumulated fees.
        undistributedLpFees = undistributedLpFees - unallocatedAccumulatedFees;

        lastLpFeeUpdate = uint32(getCurrentTime());
    }
// Solidity 0.8.9
// Allocate fees to the LPs by incrementing counters.
function _allocateLpFees(uint256 allocatedLpFees) internal {
        // Add to the total undistributed LP fees and the utilized reserves. Adding it to the utilized reserves acts to
        // track the fees while they are in transit.
        undistributedLpFees += allocatedLpFees;
        utilizedReserves += int256(allocatedLpFees);
    }
// Solidity 0.6.12
// get reference parent address matching the level tree
function getReferenceParent(address _child, uint256 _level) public view returns(address) {
        uint i;
        address pointer = _child;

        while(i < marketingLevels.length) {
            pointer = referrals[pointer];

            if (i == _level) {
                return pointer;
            }

            i++;
        }

        return address(0);
    }