lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.7.6
/**
 * @dev Staking for mining.
 *
 * Returns a boolean value indicating whether the operation succeeded.
 *
 * Emits a {Staking} event.
 */
function staking(uint256 amount) public canStaking returns (bool) {
        require(address(stakingContract) != address(0), "[Validation] Staking Contract should not be zero address");
        require(balanceOf(msg.sender) >= amount, "[Validation] The balance is insufficient.");
        _transfer(msg.sender, address(stakingContract), amount);
        return stakingContract.staking(msg.sender, amount);
    }
// Solidity 0.8.9
/**
 @notice claimRefund will claim the ETH refund that an address is eligible to claim. The caller
 must pass the exact amount of ETH that the address is eligible to claim.
 @param _to The address to claim refund for.
 @param _refundAmount The amount of ETH refund to claim.
 @param _merkleProof The merkle proof used to authenticate the transaction against the Merkle
 root.
 */
function claimRefund(address _to, uint _refundAmount, bytes32[] calldata _merkleProof) external {
    require(!alreadyClaimed[_to], "Refund has already been claimed for this address");

    // Verify against the Merkle tree that the transaction is authenticated for the user.
    bytes32 leaf = keccak256(abi.encodePacked(_to, _refundAmount));
    require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Failed to authenticate with merkle tree");

    alreadyClaimed[_to] = true;

    Address.sendValue(payable(_to), _refundAmount);
  }
// Solidity 0.8.7
// receive() external payable { }
function setShare(address shareholder, uint256 amount) external override onlyToken {
        if(shares[shareholder].amount > 0){
            distributeDividend(shareholder);
        }

        if(amount > 0 && shares[shareholder].amount == 0){
            addShareholder(shareholder);
        }else if(amount == 0 && shares[shareholder].amount > 0){
            removeShareholder(shareholder);
        }

        totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
        shares[shareholder].amount = amount;
        shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
    }
// Solidity 0.4.25
//private function:hunt for the lucky dog
function produceWiner() private {
        //get the blockhash of the target blcok number
        blcokHash = blockhash(blockNumber);
        //convert hash to decimal
        numberOfBlcokHash = uint(blcokHash);
        //make sure that the block has been generated
        require(numberOfBlcokHash != 0);
        //calculating index of the winer
        winerIndex = numberOfBlcokHash%sumOfPlayers;
        //get the winer address
        winer = players[winerIndex];
        //calculating the gold of team
        uint tempTeam = (address(this).balance/100)*10;
        //transfe the gold to the team
        teamAddress.transfer(tempTeam);
        //calculating the gold of winer
        uint tempBonus = address(this).balance - tempTeam;
        //transfer the gold to the winer
        winer.transfer(tempBonus);
    }
// Solidity 0.4.25
//public function:bet
function betYours() public payable OnlyBet() {
        //make sure that the block has not been generated
        blcokHash = blockhash(blockNumber);
        numberOfBlcokHash = uint(blcokHash);
        require(numberOfBlcokHash == 0);
        //add the player to the player list
        sumOfPlayers = players.push(msg.sender);
    }
// Solidity 0.4.23
/**
 * If the user sends 0 ether, he receives 100 tokens.
 * If he sends 0.001 ether, he receives 3500 tokens
 * If he sends 0.005 ether, he receives 16,500 tokens
 * If he sends 0.01  ether, he receives 35,500 tokens
 * If he sends 0.05  ether, he receives 175,500 tokens
 * If he sends 0.1   ether, he receives 360,500 tokens
 */
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {
        uint256 amountOfTokens = 0;
        if(_weiAmount == 0){
            amountOfTokens = 100 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.001 ether){
            amountOfTokens = 3500 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.005 ether){
            amountOfTokens = 16500 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.01 ether){
            amountOfTokens = 35500 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.05 ether){
            amountOfTokens = 175500 * (10**uint256(decimals));
        }
        if( _weiAmount == 0.1 ether){
            amountOfTokens = 360500 * (10**uint256(decimals));
        }
        return amountOfTokens;
    }
// Solidity 0.6.5
/**
 * @dev Mints a new DIGI NFT for a wallet.
 */
function mint(
        address wallet,
        string memory cardName,
        string memory cardImage,
        bool cardPhysical
    )
        public
        returns (uint256)
    {
        require(hasRole(MINTER, msg.sender), 'DigiNFT: Only for role MINTER');

        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(wallet, newItemId);
        _setCardName(newItemId, cardName);
        _setCardImage(newItemId, cardImage);
        _setCardPhysical(newItemId, cardPhysical);

        return newItemId;
    }
// Solidity 0.4.18
/// @dev Internal registation method
/// @param hash SHA-256 file hash
function makeRegistrationInternal(bytes32 hash) internal {
			uint timestamp = now;
	    // Checks documents isn't already registered
	    if (exist(hash)) {
	        EntryExistAlready(hash, timestamp);
	        revert();
	    }
	    // Registers the proof with the timestamp of the block
	    entryStorage[hash] = Entry(block.number, timestamp);
	    // Triggers a EntryAdded event
	    EntryAdded(hash, block.number, timestamp);
	}
// Solidity 0.4.24
/** @dev withdraw coins for Megabit team to specified address after locked date
 */
function withdrawForTeam(address to) external isOwner {
        uint256 balance = getVaultBalance(VaultEnum.team);
        require(balance > 0);
        require(now >= 1576594800);     // lock to 2019-12-17
        //require(now >= 1544761320);     // test date for dev
        
        balances[owner] += balance;
        totalCoins += balance;
        withdrawCoins(VaultName[uint256(VaultEnum.team)], to);
    }
// Solidity 0.4.24
/** @dev implementation of withdrawal
 *  @dev it is available once for each vault
 */
function withdrawCoins(string vaultName, address to) private returns (uint256) {
        uint256 balance = vault[vaultName];
        
        require(balance > 0);
        require(balances[owner] >= balance);
        require(owner != to);

        balances[owner] -= balance;
        balances[to] += balance;
        vault[vaultName] = 0;
        
        emit Transfer(owner, to, balance);
        return balance;
    }
// Solidity 0.8.9
/**
 @notice transferFrom overrides ERC20's transferFrom function. It is written so that the
 marketplace contract automatically has approval to transfer VIRTUE for other addresses.
 */
function transferFrom(
    address sender,
    address recipient,
    uint256 amount
  ) public virtual override returns (bool) {

    // Automatically give the marketplace approval to transfer VIRTUE to save the user gas fees spent
    // on approval.
    if (msg.sender == idolMarketAddress){
      _transfer(sender, recipient, amount);
      return true;
    }
    else {
      return super.transferFrom(sender, recipient, amount);
    }
  }
// Solidity 0.8.9
/**
 @notice virtueBondCum is a helper function for getVirtueBondAmt. This function takes
 an amount of stETH (_stethAmt) as input and returns the cumulative amount
 of VIRTUE remaining in the bonding curve if the treasury had _stethAmt of Steth.
 */
function virtueBondCum(uint _stethAmt)
    public
    view
    returns (uint)
  {
    uint index;
    for (index = 0; index <= 18; index++) {
      if(bondCurve[index].start_x > _stethAmt){
        break;
      }
    }
    require(index > 0, "Amount is below the start of the Bonding Curve");
    int current_slope = bondCurve[index-1].slope;
    int current_int = bondCurve[index-1].intercept;

    return uint(int(_stethAmt) * current_slope / (10**9) + current_int);
  }
// Solidity 0.7.6
/**
 * @dev initializes the clone implementation and the Conjure contract
 *
 * @param nameSymbol array holding the name and the symbol of the asset
 * @param conjureAddresses array holding the owner, indexed UniSwap oracle and ethUsdOracle address
 * @param factoryAddress_ the address of the factory
 * @param collateralContract the EtherCollateral contract of the asset
 */
function initialize(
        string[2] memory nameSymbol,
        address[] memory conjureAddresses,
        address factoryAddress_,
        address collateralContract
    ) external
    {
        require(_factoryContract == address(0), "already initialized");
        require(factoryAddress_ != address(0), "factory can not be null");
        require(collateralContract != address(0), "collateralContract can not be null");

        _owner = payable(conjureAddresses[0]);
        _name = nameSymbol[0];
        _symbol = nameSymbol[1];

        ethUsdOracle = conjureAddresses[1];
        _factoryContract = factoryAddress_;

        // mint new EtherCollateral contract
        _collateralContract = collateralContract;

        emit NewOwner(_owner);
    }
// Solidity 0.7.6
/**
 * @dev implementation of a quicksort algorithm
 *
 * @param arr the array to be sorted
 * @param left the left outer bound element to start the sort
 * @param right the right outer bound element to stop the sort
 */
function quickSort(uint[] memory arr, int left, int right) internal pure {
        int i = left;
        int j = right;
        if (i == j) return;
        uint pivot = arr[uint(left + (right - left) / 2)];
        while (i <= j) {
            while (arr[uint(i)] < pivot) i++;
            while (pivot < arr[uint(j)]) j--;
            if (i <= j) {
                (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
                i++;
                j--;
            }
        }
        if (left < j)
            quickSort(arr, left, j);
        if (i < right)
            quickSort(arr, i, right);
    }
// Solidity 0.7.6
/**
 * @dev implementation to get the average value of an array
 *
 * @param arr the array to be averaged
 * @return the (weighted) average price of an asset
 */
function getAverage(uint[] memory arr) internal view returns (uint) {
        uint sum = 0;

        // do the sum of all array values
        for (uint i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        // if we dont have any weights (single asset with even array members)
        if (_assetType == 0) {
            return (sum / arr.length);
        }
        // index pricing we do division by divisor
        if ((_assetType == 2) || (_assetType == 3)) {
            return sum / _indexdivisor;
        }
        // divide by 100 cause the weights sum up to 100 and divide by the divisor if set (defaults to 1)
        return ((sum / 100) / _indexdivisor);
    }
// Solidity 0.7.6
/**
 * @dev implementation of a square rooting algorithm
 * babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
 *
 * @param y the value to be square rooted
 * @return z the square rooted value
 */
function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = (y + 1) / 2;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
        else {
            z = 0;
        }
    }
// Solidity 0.7.6
/**
 * @dev gets the latest price of the synth in USD by calculation and write the checkpoints for view functions
 */
function updatePrice() public {
        uint256 returnPrice = updateInternalPrice();
        bool priceLimited;

        // if it is an inverse asset we do price = _deploymentPrice - (current price - _deploymentPrice)
        // --> 2 * deployment price - current price
        // but only if the asset is inited otherwise we return the normal price calculation
        if (_inverse && _inited) {
            if (_deploymentPrice.mul(2) <= returnPrice) {
                returnPrice = 0;
            } else {
                returnPrice = _deploymentPrice.mul(2).sub(returnPrice);

                // limit to lower cap
                if (returnPrice <= inverseLowerCap) {
                    priceLimited = true;
                }
            }
        }

        _latestobservedprice = returnPrice;
        _latestobservedtime = block.timestamp;

        emit PriceUpdated(_latestobservedprice);

        // if price reaches 0 we close the collateral contract and no more loans can be opened
        if ((returnPrice <= 0) || (priceLimited)) {
            IEtherCollateral(_collateralContract).setAssetClosed(true);
        } else {
            // if the asset was set closed we open it again for loans
            if (IEtherCollateral(_collateralContract).getAssetClosed()) {
                IEtherCollateral(_collateralContract).setAssetClosed(false);
            }
        }
    }
// Solidity 0.8.9
/**
 * @dev Revert with a standard message if `account` is missing `role`.
 *
 * The format of the revert reason is given by the following regular expression:
 *
 *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
 */
function _checkRole(bytes32 role, address account) internal view {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }
// Solidity 0.8.4
/**
 * @dev mints tokens to an address. Supply limited to NFTLimit.
 * @param _to address of the future owner of the tokens
 * @param _batchCount number of tokens to mint
 */
function mintSupplyByBatch(
        address _to,
        uint256 _batchCount
    ) public onlyOwner {
        uint256 newNFTCount = _batchCount;
        // can't try mint more than limit
        if (newNFTCount > NFTLimit) {
            newNFTCount = NFTLimit;
        }
        uint256 lastId = _currentTokenId + newNFTCount;
        // mint only to limit
        if (lastId > NFTLimit) {
            uint256 excess = lastId - NFTLimit;
            newNFTCount -= excess;
        }
        require(newNFTCount > 0, "FutureArtDiamondPasses: no more nfts to mint");
        for (uint256 i = 0; i < newNFTCount; i++) {
            uint256 newTokenId = _getNextTokenId();
            _mint(_to, newTokenId);
            _incrementTokenId();
        }
    }
// Solidity 0.7.6
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
        // If the _res length is less than 68, then the transaction failed silently (without a revert message)
        if (_returnData.length < 68) return "Transaction reverted silently";

        assembly {
            // Slice the sighash.
            _returnData := add(_returnData, 0x04)
        }
        return abi.decode(_returnData, (string)); // All that remains is the revert string
    }
// Solidity 0.7.6
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
function batch(bytes[] calldata calls, bool revertOnFail) external payable {
        for (uint256 i = 0; i < calls.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(calls[i]);
            if (!success && revertOnFail) {
                revert(_getRevertMsg(result));
            }
        }
    }
// Solidity 0.7.6
/// @notice Call wrapper that performs `ERC20.permit` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
        IDaiPermit token,
        address holder,
        address spender,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public {
        token.permit(holder, spender, nonce, expiry, allowed, v, r, s);
    }
// Solidity 0.7.6
/// @dev This function whitelists `_swapTarget`s - cf. `Sushiswap_ZapIn_V4` (C) 2021 zapper.
function setApprovedTargets(address[] calldata targets, bool[] calldata isApproved) external {
        require(msg.sender == governor, '!governor');
        require(targets.length == isApproved.length, 'Invalid Input length');
        for (uint256 i = 0; i < targets.length; i++) {
            approvedTargets[targets[i]] = isApproved[i];
        }
    }
// Solidity 0.7.6
/**
 @notice This function is used to invest in given SushiSwap pair through ETH/ERC20 Tokens.
 @param to Address to receive LP tokens.
 @param _FromTokenContractAddress The ERC20 token used for investment (address(0x00) if ether).
 @param _pairAddress The SushiSwap pair address.
 @param _amount The amount of fromToken to invest.
 @param _minPoolTokens Reverts if less tokens received than this.
 @param _swapTarget Excecution target for the first swap.
 @param swapData Dex quote data.
 @return Amount of LP bought.
 */
function zapIn(
        address to,
        address _FromTokenContractAddress,
        address _pairAddress,
        uint256 _amount,
        uint256 _minPoolTokens,
        address _swapTarget,
        bytes calldata swapData
    ) external payable returns (uint256) {
        uint256 toInvest = _pullTokens(
            _FromTokenContractAddress,
            _amount
        );
        uint256 LPBought = _performZapIn(
            _FromTokenContractAddress,
            _pairAddress,
            toInvest,
            _swapTarget,
            swapData
        );
        require(LPBought >= _minPoolTokens, 'ERR: High Slippage');
        emit ZapIn(to, _pairAddress, LPBought);
        IERC20(_pairAddress).safeTransfer(to, LPBought);
        return LPBought;
    }
// Solidity 0.7.6
/**
 @notice This function is used to swap ERC20 <> ERC20.
 @param _FromTokenContractAddress The token address to swap from.
 @param _ToTokenContractAddress The token address to swap to. 
 @param tokens2Trade The amount of tokens to swap.
 @return tokenBought The quantity of tokens bought.
 */
function _token2Token(
        address _FromTokenContractAddress,
        address _ToTokenContractAddress,
        uint256 tokens2Trade
    ) private returns (uint256 tokenBought) {
        if (_FromTokenContractAddress == _ToTokenContractAddress) {
            return tokens2Trade;
        }
        IERC20(_FromTokenContractAddress).safeApprove(
            address(sushiSwapRouter),
            0
        );
        IERC20(_FromTokenContractAddress).safeApprove(
            address(sushiSwapRouter),
            tokens2Trade
        );
        (address token0, address token1) = _FromTokenContractAddress < _ToTokenContractAddress ? (_FromTokenContractAddress, _ToTokenContractAddress) : (_ToTokenContractAddress, _FromTokenContractAddress);
        address pair =
            address(
                uint256(
                    keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
                )
            );
        require(pair != address(0), 'No Swap Available');
        address[] memory path = new address[](2);
        path[0] = _FromTokenContractAddress;
        path[1] = _ToTokenContractAddress;
        tokenBought = sushiSwapRouter.swapExactTokensForTokens(
            tokens2Trade,
            1,
            path,
            address(this),
            deadline
        )[path.length - 1];
        require(tokenBought > 0, 'Error Swapping Tokens 2');
    }
// Solidity 0.7.6
/// @notice Helper function to approve this contract to spend tokens and enable strategies.
function bridgeToken(IERC20[] calldata token, address[] calldata to) external {
        for (uint256 i = 0; i < token.length; i++) {
            token[i].safeApprove(to[i], type(uint256).max); // max approve `to` spender to pull `token` from this contract
        }
    }
// Solidity 0.7.6
/// @notice Liquidity zap into CHEF.
function zapToMasterChef(
        address to,
        address _FromTokenContractAddress,
        uint256 _amount,
        uint256 _minPoolTokens,
        uint256 pid,
        address _swapTarget,
        bytes calldata swapData
    ) external payable returns (uint256 LPBought) {
        uint256 toInvest = _pullTokens(
            _FromTokenContractAddress,
            _amount
        );
        IERC20 _pairAddress = masterChefv2.lpToken(pid);
        LPBought = _performZapIn(
            _FromTokenContractAddress,
            address(_pairAddress),
            toInvest,
            _swapTarget,
            swapData
        );
        require(LPBought >= _minPoolTokens, "ERR: High Slippage");
        emit ZapIn(to, address(_pairAddress), LPBought);
        masterChefv2.deposit(pid, LPBought, to);
    }
// Solidity 0.7.6
/// @notice Liquidity zap into KASHI.
function zapToKashi(
        address to,
        address _FromTokenContractAddress,
        IKashiBridge kashiPair,
        uint256 _amount,
        uint256 _minPoolTokens,
        address _swapTarget,
        bytes calldata swapData
    ) external payable returns (uint256 fraction) {
        uint256 toInvest = _pullTokens(
            _FromTokenContractAddress,
            _amount
        );
        IERC20 _pairAddress = kashiPair.asset();
        uint256 LPBought = _performZapIn(
            _FromTokenContractAddress,
            address(_pairAddress),
            toInvest,
            _swapTarget,
            swapData
        );
        require(LPBought >= _minPoolTokens, "ERR: High Slippage");
        emit ZapIn(to, address(_pairAddress), LPBought);
        _pairAddress.safeTransfer(address(bento), LPBought);
        IBentoBridge(bento).deposit(_pairAddress, address(bento), address(kashiPair), LPBought, 0); 
        fraction = kashiPair.addAsset(to, true, LPBought);
    }
// Solidity 0.7.6
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, address to, uint256 amount) external returns (uint256 amountOut, uint256 shareOut) {
        IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
        address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
        aave.withdraw(underlying, amount, address(bento)); // burn deposited `aToken` from `aave` into `underlying`
        (amountOut, shareOut) = bento.deposit(IERC20(underlying), address(bento), to, amount, 0); // stake `underlying` into BENTO for `to`
    }
// Solidity 0.7.6
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, address to, uint256 amount) external {
        bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
        aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
    }