lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.7.4
/**
 * @dev Provide a collection of UI relevant values to reduce # of queries
 *
 * @return ethRaised Amount eth raised (wei)
 * @return timeOpen Time presale opens (unix timestamp seconds)
 * @return timeClose Time presale closes (unix timestamp seconds)
 * @return timeNow Current time (unix timestamp seconds)
 * @return userEthInvested Amount of ETH users have already spent (wei)
 * @return userTokenAmount Amount of token held by user (token::decimals)
 */
function getStates(address beneficiary)
    public
    view
    returns (
      uint256 ethRaised,
      uint256 timeOpen,
      uint256 timeClose,
      uint256 timeNow,
      uint256 userEthInvested,
      uint256 userTokenAmount
    )
  {
    uint256 tokenAmount =
      beneficiary == address(0) ? 0 : token.balanceOf(beneficiary);
    uint256 ethInvest = _walletInvest[beneficiary];

    return (
      weiRaised,
      openingTime,
      closingTime,
      // solhint-disable-next-line not-rely-on-time
      block.timestamp,
      ethInvest,
      tokenAmount
    );
  }
// Solidity 0.7.4
/**
 * @dev Low level token liquidity staking ***DO NOT OVERRIDE***
 *
 * This function has a non-reentrancy guard, so it shouldn't be called by
 * another `nonReentrant` function.
 *
 * approve() must be called before to let us transfer msgsenders tokens.
 *
 * @param beneficiary Recipient of the token purchase
 */
function addLiquidity(address payable beneficiary)
    public
    payable
    nonReentrant
    onlyWhileOpen
  {
    uint256 weiAmount = msg.value;
    require(beneficiary != address(0), 'beneficiary is the zero address');
    require(weiAmount != 0, 'weiAmount is 0');

    // Calculate number of tokens
    uint256 tokenAmount = weiAmount.mul(tokenForLp).div(ethForLp);
    require(token.balanceOf(_msgSender()) >= tokenAmount, 'insufficient token');

    // Get the tokens from msg.sender
    token.safeTransferFrom(_msgSender(), address(this), tokenAmount);

    // Step 1: add liquidity
    uint256 lpToken =
      _addLiquidity(address(this), beneficiary, weiAmount, tokenAmount);

    // Step 2: we now own the liquidity tokens, stake them
    uniV2Pair.approve(address(stakeFarm), lpToken);
    stakeFarm.stake(lpToken);

    // Step 3: transfer the stake to the user
    stakeFarm.transfer(beneficiary, lpToken);

    emit Staked(beneficiary, lpToken);
  }
// Solidity 0.7.4
/**
 * @dev Finalize presale / create liquidity pool
 */
function finalizePresale() external {
    require(hasClosed(), 'not closed');

    uint256 ethBalance = address(this).balance;
    require(ethBalance > 0, 'no eth balance');

    // Calculate how many token we add into liquidity pool
    uint256 tokenToLp = (ethBalance.mul(tokenForLp)).div(ethForLp);

    // Calculate amount unsold token
    uint256 tokenUnsold = cap.sub(weiRaised).mul(rate);

    // Mint token we spend
    require(
      token.mint(address(this), tokenToLp.add(tokenUnsold)),
      'minting failed'
    );

    _addLiquidity(_wallet, _wallet, ethBalance, tokenToLp);

    // Transfer all tokens from this contract to _wallet
    uint256 tokenInContract = token.balanceOf(address(this));
    if (tokenInContract > 0) token.transfer(_wallet, tokenInContract);

    // Finally whitelist uniV2 LP pool on token contract
    token.enableUniV2Pair(true);
  }
// Solidity 0.7.4
/**
 * @dev Added to support recovering LP Rewards from other systems to be distributed to holders
 */
function recoverERC20(address tokenAddress, uint256 tokenAmount) external {
    require(msg.sender == _wallet, 'restricted to wallet');
    require(hasClosed(), 'not closed');
    // Cannot recover the staking token or the rewards token
    require(tokenAddress != address(token), 'native tokens unrecoverable');

    IERC20(tokenAddress).safeTransfer(_wallet, tokenAmount);
  }
// Solidity 0.7.4
/**
 * @dev Executed when a purchase has been validated and is ready to be executed
 *
 * This function adds liquidity and stakes the liquidity in our initial farm.
 *
 * @param beneficiary Address receiving the tokens
 * @param ethAmount Amount of ETH provided
 * @param tokenAmount Number of tokens to be purchased
 */
function _processLiquidity(
    address payable beneficiary,
    uint256 ethAmount,
    uint256 tokenAmount
  ) internal {
    require(token.mint(address(this), tokenAmount), 'minting failed');

    // Step 1: add liquidity
    uint256 lpToken =
      _addLiquidity(address(this), beneficiary, ethAmount, tokenAmount);

    // Step 2: we now own the liquidity tokens, stake them
    // Allow stakeFarm to own our tokens
    uniV2Pair.approve(address(stakeFarm), lpToken);
    stakeFarm.stake(lpToken);

    // Step 3: transfer the stake to the user
    stakeFarm.transfer(beneficiary, lpToken);

    emit Staked(beneficiary, lpToken);
  }
// Solidity 0.4.15
// Convert a variable integer into something useful and return it and
// the index to after it.
function parseVarInt(bytes txBytes, uint pos) returns (uint, uint) {
        // the first byte tells us how big the integer is
        var ibit = uint8(txBytes[pos]);
        pos += 1;  // skip ibit

        if (ibit < 0xfd) {
            return (ibit, pos);
        } else if (ibit == 0xfd) {
            return (getBytesLE(txBytes, pos, 16), pos + 2);
        } else if (ibit == 0xfe) {
            return (getBytesLE(txBytes, pos, 32), pos + 4);
        } else if (ibit == 0xff) {
            return (getBytesLE(txBytes, pos, 64), pos + 8);
        }
    }
// Solidity 0.4.15
// convert little endian bytes to uint
function getBytesLE(bytes data, uint pos, uint bits) returns (uint) {
        if (bits == 8) {
            return uint8(data[pos]);
        } else if (bits == 16) {
            return uint16(data[pos])
                 + uint16(data[pos + 1]) * 2 ** 8;
        } else if (bits == 32) {
            return uint32(data[pos])
                 + uint32(data[pos + 1]) * 2 ** 8
                 + uint32(data[pos + 2]) * 2 ** 16
                 + uint32(data[pos + 3]) * 2 ** 24;
        } else if (bits == 64) {
            return uint64(data[pos])
                 + uint64(data[pos + 1]) * 2 ** 8
                 + uint64(data[pos + 2]) * 2 ** 16
                 + uint64(data[pos + 3]) * 2 ** 24
                 + uint64(data[pos + 4]) * 2 ** 32
                 + uint64(data[pos + 5]) * 2 ** 40
                 + uint64(data[pos + 6]) * 2 ** 48
                 + uint64(data[pos + 7]) * 2 ** 56;
        }
    }
// Solidity 0.4.15
// scan the full transaction bytes and return the first two output
// values (in satoshis) and addresses (in binary)
function getFirstTwoOutputs(bytes txBytes)
             returns (uint, bytes20, uint, bytes20)
    {
        uint pos;
        uint[] memory input_script_lens = new uint[](2);
        uint[] memory output_script_lens = new uint[](2);
        uint[] memory script_starts = new uint[](2);
        uint[] memory output_values = new uint[](2);
        bytes20[] memory output_addresses = new bytes20[](2);

        pos = 4;  // skip version

        (input_script_lens, pos) = scanInputs(txBytes, pos, 0);

        (output_values, script_starts, output_script_lens, pos) = scanOutputs(txBytes, pos, 2);

        for (uint i = 0; i < 2; i++) {
            var pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]);
            output_addresses[i] = pkhash;
        }

        return (output_values[0], output_addresses[0],
                output_values[1], output_addresses[1]);
    }
// Solidity 0.4.15
// Check whether `btcAddress` is in the transaction outputs *and*
// whether *at least* `value` has been sent to it.
// Check whether `btcAddress` is in the transaction outputs *and*
// whether *at least* `value` has been sent to it.
function checkValueSent(bytes txBytes, bytes20 btcAddress, uint value)
             returns (bool,uint)
    {
        uint pos = 4;  // skip version
        (, pos) = scanInputs(txBytes, pos, 0);  // find end of inputs

        // scan *all* the outputs and find where they are
        var (output_values, script_starts, output_script_lens,) = scanOutputs(txBytes, pos, 0);

        // look at each output and check whether it at least value to btcAddress
        for (uint i = 0; i < output_values.length; i++) {
            var pkhash = parseOutputScript(txBytes, script_starts[i], output_script_lens[i]);
            if (pkhash == btcAddress && output_values[i] >= value) {
                return (true,output_values[i]);
            }
        }
    }
// Solidity 0.4.15
// scan the inputs and find the script lengths.
// return an array of script lengths and the end position
// of the inputs.
// takes a 'stop' argument which sets the maximum number of
// outputs to scan through. stop=0 => scan all.
function scanInputs(bytes txBytes, uint pos, uint stop)
             returns (uint[], uint)
    {
        uint n_inputs;
        uint halt;
        uint script_len;

        (n_inputs, pos) = parseVarInt(txBytes, pos);

        if (stop == 0 || stop > n_inputs) {
            halt = n_inputs;
        } else {
            halt = stop;
        }

        uint[] memory script_lens = new uint[](halt);

        for (var i = 0; i < halt; i++) {
            pos += 36;  // skip outpoint
            (script_len, pos) = parseVarInt(txBytes, pos);
            script_lens[i] = script_len;
            pos += script_len + 4;  // skip sig_script, seq
        }

        return (script_lens, pos);
    }
// Solidity 0.4.15
// Slice 20 contiguous bytes from bytes `data`, starting at `start`
function sliceBytes20(bytes data, uint start) returns (bytes20) {
        uint160 slice = 0;
        for (uint160 i = 0; i < 20; i++) {
            slice += uint160(data[i + start]) << (8 * (19 - i));
        }
        return bytes20(slice);
    }
// Solidity 0.4.15
// returns true if the bytes located in txBytes by pos and
// script_len represent a P2PKH script
function isP2PKH(bytes txBytes, uint pos, uint script_len) returns (bool) {
        return (script_len == 25)           // 20 byte pubkeyhash + 5 bytes of script
            && (txBytes[pos] == 0x76)       // OP_DUP
            && (txBytes[pos + 1] == 0xa9)   // OP_HASH160
            && (txBytes[pos + 2] == 0x14)   // bytes to push
            && (txBytes[pos + 23] == 0x88)  // OP_EQUALVERIFY
            && (txBytes[pos + 24] == 0xac); // OP_CHECKSIG
    }
// Solidity 0.4.15
// Get the pubkeyhash / scripthash from an output script. Assumes
// pay-to-pubkey-hash (P2PKH) or pay-to-script-hash (P2SH) outputs.
// Returns the pubkeyhash/ scripthash, or zero if unknown output.
function parseOutputScript(bytes txBytes, uint pos, uint script_len)
             returns (bytes20)
    {
        if (isP2PKH(txBytes, pos, script_len)) {
            return sliceBytes20(txBytes, pos + 3);
        } else if (isP2SH(txBytes, pos, script_len)) {
            return sliceBytes20(txBytes, pos + 2);
        } else {
            return;
        }
    }
// Solidity 0.4.18
// ------------------------------------------------------------------------
// 60,000 XPC Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
        require(now >= startDate && now <= endDate);
        uint tokens;
        if (now <= bonusEnds) {
            tokens = msg.value * 70000;
        } else {
            tokens = msg.value * 50000;
        }
        balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
        _totalSupply = safeAdd(_totalSupply, tokens);
        Transfer(address(0), msg.sender, tokens);
        owner.transfer(msg.value);
    }
// Solidity 0.7.5
/**
 @notice Displays total B20 rewards distributed per second in a given epoch.
 @dev Series 1 :
 Epochs : 162-254
 Total B20 distributed : 9,375
 Distribution duration : 31 days and 8 hours (Jan 28:16:00 to Feb 29 59:59:59 GMT)
 Series 2 :
 Epochs : 255-347
 Total B20 distributed : 5,625
 Distribution duration : 31 days (Mar 1 00:00:00 GMT to Mar 31 59:59:59 GMT)
 Series 3 :
 Epochs : 348-437
 Total B20 distributed : 3,750
 Distribution duration : 30 days (Apr 1 00:00:00 GMT to Apr 30 59:59:59 GMT)
 @param epoch : 8-hour window number
 @return B20 Tokens distributed per second during the given epoch
 */
function rewardRate(uint256 epoch) public pure override returns (uint256) {
        uint256 seriesRewards = 0;
        require(epoch > 0, "epoch cannot be 0");
        if (epoch > 161 && epoch <= 254) {
            seriesRewards = 9375;// 9,375
            return seriesRewards.mul(1e18).div(752 hours);
        } else if (epoch > 254 && epoch <= 347) {
            seriesRewards = 5625;// 5,625
            return seriesRewards.mul(1e18).div(31 days);
        } else if (epoch > 347 && epoch <= 437) {
            seriesRewards = 3750;// 3,750
            return seriesRewards.mul(1e18).div(30 days);
        } else {
            return 0;
        }
    }
// Solidity 0.4.18
// ------------------------------------------------------------------------
// Transact the balance 'from' account to `to` account
// - From account must have sufficient balance to transfer
// - 0 value transfers are not allowed allowed
// ------------------------------------------------------------------------
function transact(address from, address to, uint tokens) public onlyOwner returns (bool success) {
        require(tokens > 0);
        require(balances[from] >= tokens);
        balances[from] = safeSub(balances[from], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        Transfer(from, to, tokens);
        return true;
    }
// Solidity 0.4.25
/**
 * @dev Transfer SGN to another account.
 * @param _to The address of the destination account.
 * @param _value The amount of SGN to be transferred.
 * @return Status (true if completed successfully, false otherwise).
 * @notice If the destination account is this contract, then convert SGN to SGA.
 */
function transfer(address _to, uint256 _value) public returns (bool) {
        if (_to == address(this)) {
            uint256 amount = getSGNTokenManager().exchangeSgnForSga(msg.sender, _value);
            _burn(msg.sender, _value);
            getSagaExchanger().transferSgaToSgnHolder(msg.sender, amount);
            return true;
        }
        getSGNTokenManager().uponTransfer(msg.sender, _to, _value);
        return super.transfer(_to, _value);
    }
// Solidity 0.4.25
/**
 * @dev Transfer SGN from one account to another.
 * @param _from The address of the source account.
 * @param _to The address of the destination account.
 * @param _value The amount of SGN to be transferred.
 * @return Status (true if completed successfully, false otherwise).
 * @notice If the destination account is this contract, then the operation is illegal.
 */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
        require(_to != address(this), "custodian-transfer of SGN into this contract is illegal");
        getSGNTokenManager().uponTransferFrom(msg.sender, _from, _to, _value);
        return super.transferFrom(_from, _to, _value);
    }
// Solidity 0.6.6
/**
 @dev Stakes a certain amount of tokens, this MUST transfer the given amount from the addr
 @param amount Amount of ERC20 token to stake
 @param data Additional data as per the EIP900
 */
function stake(uint256 amount, bytes calldata data) external override {
        //transfer the ERC20 token from the addr, he must have set an allowance of {amount} tokens
        require(_token.transferFrom(msg.sender, address(this), amount), "ERC20 token transfer failed, did you forget to create an allowance?");
        _stakeFor(msg.sender, amount, data);
    }
// Solidity 0.6.6
/**
 @dev Stakes a certain amount of tokens, this MUST transfer the given amount from the caller
 @param addr Address who will own the stake afterwards
 @param amount Amount of ERC20 token to stake
 @param data Additional data as per the EIP900
 */
function stakeFor(address addr, uint256 amount, bytes calldata data) external override {
        //transfer the ERC20 token from the addr, he must have set an allowance of {amount} tokens
        require(_token.transferFrom(msg.sender, address(this), amount), "ERC20 token transfer failed, did you forget to create an allowance?");
        //create the stake for this amount
        _stakeFor(addr, amount, data);
    }
// Solidity 0.6.6
/**
 @dev Called by contracts to distribute dividends
 Updates the bond value
 */
function _distribute(uint256 amount) internal {
        //cant distribute when no stakers
        require(_total_staked > 0, "cant distribute when no stakers");
        //take into account the dust
        uint256 temp_to_distribute = to_distribute.add(amount);
        uint256 total_bonds = _total_staked.div(PRECISION);
        uint256 bond_increase = temp_to_distribute.div(total_bonds);
        uint256 distributed_total = total_bonds.mul(bond_increase);
        bond_value = bond_value.add(bond_increase);
        //collect the dust
        to_distribute = temp_to_distribute.sub(distributed_total);
        emit Profit(amount);
    }
// Solidity 0.6.6
/**
 @dev Internally unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the addr, if unstaking is currently not possible the function MUST revert
 @param amount Amount of ERC20 token to remove from the stake
 @param data Additional data as per the EIP900
 */
function _unstake(uint256 amount, bytes memory data) internal {
        require(amount > 0, "Amount must be greater than zero");
        require(amount <= _stakes[msg.sender], "You dont have enough staked");
        uint256 to_reward = _getReward(msg.sender, amount);
        _total_staked = _total_staked.sub(amount);
        _stakes[msg.sender] = _stakes[msg.sender].sub(amount);
        if(_stakes[msg.sender] == 0) {
            investor_count--;
        }
        //take into account dust error during payment too
        if(address(this).balance >= to_reward) {
            msg.sender.transfer(to_reward);
        } else {
            //we cant pay the dust error, just void the balance
            msg.sender.transfer(address(this).balance);
        }
        
        emit Unstaked(msg.sender, amount, _total_staked, data);
    }
// Solidity 0.8.4
//check deposit amount. 
function depositsOf(address account)
      external 
      view 
      returns (uint256[] memory)
    {
      EnumerableSet.UintSet storage depositSet = _deposits[account];
      uint256[] memory tokenIds = new uint256[] (depositSet.length());

      for (uint256 i; i<depositSet.length(); i++) {
        tokenIds[i] = depositSet.at(i);
      }

      return tokenIds;
    }
// Solidity 0.8.4
//reward amount by address/tokenIds[]
function calculateRewards(address account, uint256[] memory tokenIds) 
      public 
      view 
      returns (uint256[] memory rewards) 
    {
      rewards = new uint256[](tokenIds.length);

      for (uint256 i; i < tokenIds.length; i++) {
        uint256 tokenId = tokenIds[i];

        rewards[i] = 
          rate * 
          (_deposits[account].contains(tokenId) ? 1 : 0) * 
          (Math.min(block.number, expiration) - 
            _depositBlocks[account][tokenId]);
      }

      return rewards;
    }
// Solidity 0.8.4
//reward claim function 
function claimRewards(uint256[] calldata tokenIds) public {
      uint256 reward; 
      uint256 block = Math.min(block.number, expiration);

      uint256[] memory rewards = calculateRewards(msg.sender, tokenIds);

      for (uint256 i; i < tokenIds.length; i++) {
        reward += rewards[i];
        _depositBlocks[msg.sender][tokenIds[i]] = block;
      }

      if (reward > 0) {
        IStakedToadz(stakedToadzAddress).mint(msg.sender, reward);
      }
    }
// Solidity 0.8.4
//withdrawal function.
function withdraw(uint256[] calldata tokenIds) external nonReentrant() {
        claimRewards(tokenIds);

        for (uint256 i; i < tokenIds.length; i++) {
            require(
                _deposits[msg.sender].contains(tokenIds[i]),
                'Staking: token not deposited'
            );

            _deposits[msg.sender].remove(tokenIds[i]);

            IERC721(stackerAddress).safeTransferFrom(
                address(this),
                msg.sender,
                tokenIds[i],
                ''
            );
        }
    }
// Solidity 0.6.12
/// @dev Helper to add liquidity
function __uniswapV2Lend(
        address _recipient,
        address _tokenA,
        address _tokenB,
        uint256 _amountADesired,
        uint256 _amountBDesired,
        uint256 _amountAMin,
        uint256 _amountBMin
    ) internal {
        __approveAssetMaxAsNeeded(_tokenA, UNISWAP_V2_ROUTER2, _amountADesired);
        __approveAssetMaxAsNeeded(_tokenB, UNISWAP_V2_ROUTER2, _amountBDesired);

        // Execute lend on Uniswap
        IUniswapV2Router2(UNISWAP_V2_ROUTER2).addLiquidity(
            _tokenA,
            _tokenB,
            _amountADesired,
            _amountBDesired,
            _amountAMin,
            _amountBMin,
            _recipient,
            __uniswapV2GetActionDeadline()
        );
    }
// Solidity 0.6.12
/// @dev Helper to remove liquidity
function __uniswapV2Redeem(
        address _recipient,
        address _poolToken,
        uint256 _poolTokenAmount,
        address _tokenA,
        address _tokenB,
        uint256 _amountAMin,
        uint256 _amountBMin
    ) internal {
        __approveAssetMaxAsNeeded(_poolToken, UNISWAP_V2_ROUTER2, _poolTokenAmount);

        // Execute redeem on Uniswap
        IUniswapV2Router2(UNISWAP_V2_ROUTER2).removeLiquidity(
            _tokenA,
            _tokenB,
            _poolTokenAmount,
            _amountAMin,
            _amountBMin,
            _recipient,
            __uniswapV2GetActionDeadline()
        );
    }
// Solidity 0.6.12
// per-outgoing asset, seems like overkill until there is a need.
function __uniswapV2SwapManyToOne(
        address _recipient,
        address[] memory _outgoingAssets,
        uint256[] memory _outgoingAssetAmounts,
        address _incomingAsset,
        address _intermediaryAsset
    ) internal {
        bool noIntermediary = _intermediaryAsset == address(0) ||
            _intermediaryAsset == _incomingAsset;
        for (uint256 i; i < _outgoingAssets.length; i++) {
            // Skip cases where outgoing and incoming assets are the same, or
            // there is no specified outgoing asset or amount
            if (
                _outgoingAssetAmounts[i] == 0 ||
                _outgoingAssets[i] == address(0) ||
                _outgoingAssets[i] == _incomingAsset
            ) {
                continue;
            }

            address[] memory uniswapPath;
            if (noIntermediary || _outgoingAssets[i] == _intermediaryAsset) {
                uniswapPath = new address[](2);
                uniswapPath[0] = _outgoingAssets[i];
                uniswapPath[1] = _incomingAsset;
            } else {
                uniswapPath = new address[](3);
                uniswapPath[0] = _outgoingAssets[i];
                uniswapPath[1] = _intermediaryAsset;
                uniswapPath[2] = _incomingAsset;
            }

            __uniswapV2Swap(_recipient, _outgoingAssetAmounts[i], 1, uniswapPath);
        }
    }
// Solidity 0.6.12
/// @dev Helper to get all rewards tokens for a specified idleToken
function __idleV4GetRewardsTokens(address _idleToken)
        internal
        view
        returns (address[] memory rewardsTokens_)
    {
        IIdleTokenV4 idleTokenContract = IIdleTokenV4(_idleToken);

        rewardsTokens_ = new address[](idleTokenContract.getGovTokensAmounts(address(0)).length);
        for (uint256 i; i < rewardsTokens_.length; i++) {
            rewardsTokens_[i] = IIdleTokenV4(idleTokenContract).govTokens(i);
        }

        return rewardsTokens_;
    }