lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.3
/// @dev Allows to swap/replace an owner from the Safe with another address.
///      This can only be done via a Safe transaction.
/// @param prevOwner Owner that pointed to the owner to be replaced in the linked list
/// @param oldOwner Owner address to be replaced.
/// @param newOwner New owner address.
function swapOwner(address prevOwner, address oldOwner, address newOwner)
        public
        authorized
    {
        // Owner address cannot be null.
        require(newOwner != address(0) && newOwner != SENTINEL_OWNERS, "Invalid owner address provided");
        // No duplicate owners allowed.
        require(owners[newOwner] == address(0), "Address is already an owner");
        // Validate oldOwner address and check that it corresponds to owner index.
        require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, "Invalid owner address provided");
        require(owners[prevOwner] == oldOwner, "Invalid prevOwner, owner pair provided");
        owners[newOwner] = owners[oldOwner];
        owners[prevOwner] = newOwner;
        owners[oldOwner] = address(0);
        emit RemovedOwner(oldOwner);
        emit AddedOwner(newOwner);
    }
// Solidity 0.5.3
/// @dev Allows to update the number of required confirmations by Safe owners.
///      This can only be done via a Safe transaction.
/// @param _threshold New threshold.
function changeThreshold(uint256 _threshold)
        public
        authorized
    {
        // Validate that threshold is smaller than number of owners.
        require(_threshold <= ownerCount, "Threshold cannot exceed owner count");
        // There has to be at least one Safe owner.
        require(_threshold >= 1, "Threshold needs to be greater than 0");
        threshold = _threshold;
        emit ChangedThreshold(threshold);
    }
// Solidity 0.5.3
/// @dev Returns array of owners.
/// @return Array of Safe owners.
function getOwners()
        public
        view
        returns (address[] memory)
    {
        address[] memory array = new address[](ownerCount);

        // populate return array
        uint256 index = 0;
        address currentOwner = owners[SENTINEL_OWNERS];
        while(currentOwner != SENTINEL_OWNERS) {
            array[index] = currentOwner;
            currentOwner = owners[currentOwner];
            index ++;
        }
        return array;
    }
// Solidity 0.5.3
/// @dev Setup function sets initial storage of contract.
/// @param _owners List of Safe owners.
/// @param _threshold Number of required confirmations for a Safe transaction.
/// @param to Contract address for optional delegate call.
/// @param data Data payload for optional delegate call.
function setupSafe(address[] memory _owners, uint256 _threshold, address to, bytes memory data)
        internal
    {
        setupOwners(_owners, _threshold);
        // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules
        setupModules(to, data);
    }
// Solidity 0.5.3
/// @dev Recovers address who signed the message 
/// @param messageHash operation ethereum signed message hash
/// @param messageSignature message `txHash` signature
/// @param pos which signature to read
function recoverKey (
        bytes32 messageHash, 
        bytes memory messageSignature,
        uint256 pos
    )
        internal
        pure
        returns (address) 
    {
        uint8 v;
        bytes32 r;
        bytes32 s;
        (v, r, s) = signatureSplit(messageSignature, pos);
        return ecrecover(messageHash, v, r, s);
    }
// Solidity 0.5.3
/// @dev divides bytes signature into `uint8 v, bytes32 r, bytes32 s`
/// @param pos which signature to read
/// @param signatures concatenated rsv signatures
function signatureSplit(bytes memory signatures, uint256 pos)
        internal
        pure
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        // The signature format is a compact form of:
        //   {bytes32 r}{bytes32 s}{uint8 v}
        // Compact means, uint8 is not padded to 32 bytes.
        // solium-disable-next-line security/no-inline-assembly
        assembly {
            let signaturePos := mul(0x41, pos)
            r := mload(add(signatures, add(signaturePos, 0x20)))
            s := mload(add(signatures, add(signaturePos, 0x40)))
            // Here we are loading the last 32 bytes, including 31 bytes
            // of 's'. There is no 'mload8' to do this.
            //
            // 'byte' is not working due to the Solidity parser, so lets
            // use the second best option, 'and'
            v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
        }
    }
// Solidity 0.7.5
/// @dev _issueLPTokensForFloat
/// @param _token The address of target token.
/// @param _transaction The recevier address and amount.
/// @param _zerofee The flag to accept zero fees.
/// @param _txid The txid which is for recording.
function _issueLPTokensForFloat(
        address _token,
        bytes32 _transaction,
        bool _zerofee,
        bytes32 _txid
    ) internal returns (bool) {
        require(!isTxUsed(_txid), "The txid is already used");
        require(_transaction != 0x0, "The transaction is not valid");
        // Define target address which is recorded on the tx data (20 bytes)
        // Define amountOfFloat which is recorded top on tx data (12 bytes)
        (address to, uint256 amountOfFloat) = _splitToValues(_transaction);
        // Calculate the amount of LP token
        uint256 nowPrice = getCurrentPriceLP();
        uint256 amountOfLP = amountOfFloat.mul(priceDecimals).div(nowPrice);
        uint256 depositFeeRate = getDepositFeeRate(_token, amountOfFloat);
        uint256 depositFees = depositFeeRate != 0
            ? amountOfLP.mul(depositFeeRate).div(10000)
            : 0;

        if (_zerofee && depositFees != 0) {
            revert();
        }
        // Send LP tokens to LP
        IBurnableToken(lpToken).mint(to, amountOfLP.sub(depositFees));
        // Add deposit fees
        lockedLPTokensForNode = lockedLPTokensForNode.add(depositFees);
        // Add float amount
        _addFloat(_token, amountOfFloat);
        _addUsedTx(_txid);
        emit IssueLPTokensForFloat(
            to,
            amountOfFloat,
            amountOfLP,
            nowPrice,
            depositFees,
            _txid
        );
        return true;
    }
// Solidity 0.7.5
/// @dev _checkFlips checks whether the fees are activated.
/// @param _token The address of target token.
/// @param _amountOfFloat The amount of float.
function _checkFlips(address _token, uint256 _amountOfFloat)
        internal
        view
        returns (uint8)
    {
        (uint256 reserveA, uint256 reserveB) = getFloatReserve(
            address(0),
            WBTC_ADDR
        );
        uint256 threshold = reserveA
            .add(reserveB)
            .add(_amountOfFloat)
            .mul(2)
            .div(3);
        if (_token == WBTC_ADDR && reserveB.add(_amountOfFloat) >= threshold) {
            return 1; // BTC float insufficient
        }
        if (_token == address(0) && reserveA.add(_amountOfFloat) >= threshold) {
            return 2; // WBTC float insufficient
        }
        return 0;
    }
// Solidity 0.5.3
/// @dev Allows to estimate a Safe transaction.
///      This method is only meant for estimation purpose, therfore two different protection mechanism against execution in a transaction have been made:
///      1.) The method can only be called from the safe itself
///      2.) The response is returned with a revert
///      When estimating set `from` to the address of the safe.
///      Since the `estimateGas` function includes refunds, call this method to get an estimated of the costs that are deducted from the safe with `execTransaction`
/// @param to Destination address of Safe transaction.
/// @param value Ether value of Safe transaction.
/// @param data Data payload of Safe transaction.
/// @param operation Operation type of Safe transaction.
/// @return Estimate without refunds and overhead fees (base transaction and payload data gas costs).
function requiredTxGas(address to, uint256 value, bytes calldata data, Enum.Operation operation)
        external
        authorized
        returns (uint256)
    {
        uint256 startGas = gasleft();
        // We don't provide an error message here, as we use it to return the estimate
        // solium-disable-next-line error-reason
        require(execute(to, value, data, operation, gasleft()));
        uint256 requiredGas = startGas - gasleft();
        // Convert response to string and return via error message
        revert(string(abi.encodePacked(requiredGas)));
    }
// Solidity 0.5.3
/**
 * @dev Should return whether the signature provided is valid for the provided data
 * @param _data Arbitrary length data signed on the behalf of address(this)
 * @param _signature Signature byte array associated with _data
 * @return a bool upon valid or invalid signature with corresponding _data
 */
function isValidSignature(bytes calldata _data, bytes calldata _signature)
        external
        returns (bool isValid)
    {
        bytes32 messageHash = getMessageHash(_data);
        if (_signature.length == 0) {
            isValid = signedMessages[messageHash] != 0;
        } else {
            // consumeHash needs to be false, as the state should not be changed
            isValid = checkSignatures(messageHash, _data, _signature, false);
        }
    }
// Solidity 0.5.3
/// @dev Returns the bytes that are hashed to be signed by owners.
/// @param to Destination address.
/// @param value Ether value.
/// @param data Data payload.
/// @param operation Operation type.
/// @param safeTxGas Fas that should be used for the safe transaction.
/// @param dataGas Gas costs for data used to trigger the safe transaction.
/// @param gasPrice Maximum gas price that should be used for this transaction.
/// @param gasToken Token address (or 0 if ETH) that is used for the payment.
/// @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).
/// @param _nonce Transaction nonce.
/// @return Transaction hash bytes.
function encodeTransactionData(
        address to, 
        uint256 value, 
        bytes memory data, 
        Enum.Operation operation, 
        uint256 safeTxGas, 
        uint256 dataGas, 
        uint256 gasPrice,
        address gasToken,
        address refundReceiver,
        uint256 _nonce
    )
        public
        view
        returns (bytes memory)
    {
        bytes32 safeTxHash = keccak256(
            abi.encode(SAFE_TX_TYPEHASH, to, value, keccak256(data), operation, safeTxGas, dataGas, gasPrice, gasToken, refundReceiver, _nonce)
        );
        return abi.encodePacked(byte(0x19), byte(0x01), domainSeparator, safeTxHash);
    }
// Solidity 0.6.9
// ============ DPP Functions (create & reset) ============
function createDODOPrivatePool(
        address baseToken,
        address quoteToken,
        uint256 baseInAmount,
        uint256 quoteInAmount,
        uint256 lpFeeRate,
        uint256 i,
        uint256 k,
        bool isOpenTwap,
        uint256 deadLine
    )
        external
        override
        payable
        preventReentrant
        judgeExpired(deadLine)
        returns (address newPrivatePool)
    {
        newPrivatePool = IDODOV2(_DPP_FACTORY_).createDODOPrivatePool();

        address _baseToken = baseToken;
        address _quoteToken = quoteToken;
        _deposit(msg.sender, newPrivatePool, _baseToken, baseInAmount, _baseToken == _ETH_ADDRESS_);
        _deposit(
            msg.sender,
            newPrivatePool,
            _quoteToken,
            quoteInAmount,
            _quoteToken == _ETH_ADDRESS_
        );

        if (_baseToken == _ETH_ADDRESS_) _baseToken = _WETH_;
        if (_quoteToken == _ETH_ADDRESS_) _quoteToken = _WETH_;

        IDODOV2(_DPP_FACTORY_).initDODOPrivatePool(
            newPrivatePool,
            msg.sender,
            _baseToken,
            _quoteToken,
            lpFeeRate,
            k,
            i,
            isOpenTwap
        );
    }
// Solidity 0.5.3
/// @dev Setup function sets initial storage of contract.
/// @param dx DutchX Proxy Address.
/// @param tokens List of whitelisted tokens.
/// @param operators List of addresses that can operate the module.
/// @param _manager Address of the manager, the safe contract.
function setup(address dx, address[] memory tokens, address[] memory operators, address payable _manager)
        public
    {
        require(address(manager) == address(0), "Manager has already been set");
        if (_manager == address(0)){
            manager = ModuleManager(msg.sender);
        }
        else{
            manager = ModuleManager(_manager);
        }

        dutchXAddress = dx;

        for (uint256 i = 0; i < tokens.length; i++) {
            address token = tokens[i];
            require(token != address(0), "Invalid token provided");
            isWhitelistedToken[token] = true;
        }

        whitelistedTokens = tokens;

        for (uint256 i = 0; i < operators.length; i++) {
            address operator = operators[i];
            require(operator != address(0), "Invalid operator address provided");
            isOperator[operator] = true;
        }

        whitelistedOperators = operators;
    }
// Solidity 0.5.3
/// @dev Allows to remove token from whitelist. This can only be done via a Safe transaction.
/// @param token ERC20 token address.
function removeFromWhitelist(address token)
        public
        authorized
    {
        require(isWhitelistedToken[token], "Token is not whitelisted");
        isWhitelistedToken[token] = false;

        for (uint i = 0; i<whitelistedTokens.length - 1; i++)
            if(whitelistedTokens[i] == token){
                whitelistedTokens[i] = whitelistedTokens[whitelistedTokens.length-1];
                break;
            }
        whitelistedTokens.length -= 1;
    }
// Solidity 0.5.12
/**
 * @dev Configures a domain.
 * @param name The name to configure.
 * @param minion The address of the Minion who can assign subdomains
 * @param _owner The address to assign ownership of this domain to.
 */
function configureDomainFor(string memory name, address minion, address _owner) public not_stopped owner_only(keccak256(bytes(name))) {
        bytes32 label = keccak256(bytes(name));
        Domain storage domain = domains[label];

        if (Registrar(registrar).ownerOf(uint256(label)) != address(this)) {
            Registrar(registrar).transferFrom(msg.sender, address(this), uint256(label));
            Registrar(registrar).reclaim(uint256(label), address(this));
        }

        if (domain.owner != _owner) {
            domain.owner = _owner;
        }

        if (keccak256(abi.encodePacked(domain.name)) != label) {
            // New listing
            domain.name = name;
        }

        domain.minion = minion;
        domain.moloch = IMinion(minion).moloch();

        emit DomainConfigured(label, name, minion);
    }
// Solidity 0.5.12
/**
 * @dev Migrates the domain to a new registrar.
 * @param name The name of the domain to migrate.
 */
function migrate(string memory name) public owner_only(keccak256(bytes(name))) {
        require(stopped);
        require(migration != address(0x0));

        bytes32 label = keccak256(bytes(name));
        Domain storage domain = domains[label];

        Registrar(registrar).approve(migration, uint256(label));

        MinionSubdomainRegistrar(migration).configureDomainFor(
            domain.name,
            domain.minion,
            domain.owner
        );

        delete domains[label];

        emit DomainTransferred(label, name);
    }
// Solidity 0.5.12
/**
 * @dev Registers a subdomain.
 * @param label The label hash of the domain to register a subdomain of.
 * @param subdomain The desired subdomain label.
 * @param _subdomainOwner The account that should own the newly configured subdomain.
 */
function register(bytes32 label, string calldata subdomain, address _subdomainOwner, address resolver) external not_stopped {
        address subdomainOwner = _subdomainOwner;
        bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label));
        bytes32 subdomainLabel = keccak256(bytes(subdomain));

        // Subdomain must not be registered already.
        require(ens.owner(keccak256(abi.encodePacked(domainNode, subdomainLabel))) == address(0));

        Domain storage domain = domains[label];

        // Domain must be available for registration
        require(keccak256(abi.encodePacked(domain.name)) == label);

        // Use msg.sender if _subdomainOwner is not set
        if (subdomainOwner == address(0x0)) {
            subdomainOwner = msg.sender;
        }

        // Domain can only be registered by Minion or by members (and only for members)
        if (msg.sender != domain.minion) {
          // If msg.sender is not minion check that the msg.sender and new owner are members
          ( , uint256 ownerStakes, , , , ) = IMoloch(domain.moloch).members(subdomainOwner);
          ( , uint256 senderStakes, , , , ) = IMoloch(domain.moloch).members(msg.sender);
          require(senderStakes > 0 && ownerStakes > 0);
        }

        doRegistration(domainNode, subdomainLabel, subdomainOwner, Resolver(resolver));

        emit NewRegistration(label, subdomain, subdomainOwner);
    }
// Solidity 0.8.10
/**
 * @notice Changes the boosted NFT ids that receive
 *         a bigger daily reward
 *
 * @dev Restricted to contract owner
 *
 * @param _newBoostedNftIds the new boosted NFT ids
 */
function setBoostedNftIds(uint256[] memory _newBoostedNftIds) public onlyOwner {
    // Create array to store old boosted NFTs and emit
    // event later
    uint256[] memory oldBoostedNftIds = new uint256[](boostedNftIds.length());

    // Empty boosted NFT ids set
    for (uint256 i = 0; boostedNftIds.length() > 0; i++) {
      // Get a value from the set
      // Since set length is > 0 it is guaranteed
      // that there is a value at index 0
      uint256 value = boostedNftIds.at(0);

      // Remove the value
      boostedNftIds.remove(value);

      // Store the value to the old boosted NFT ids
      // list to later emit event
      oldBoostedNftIds[i] = value;
    }

    // Emit event
    emit BoostedNftIdsChanged(msg.sender, oldBoostedNftIds, _newBoostedNftIds);

    // Enumerate new boosted NFT ids
    for (uint256 i = 0; i < _newBoostedNftIds.length; i++) {
      uint256 boostedNftId = _newBoostedNftIds[i];

      // Add boosted NFT id to set
      boostedNftIds.add(boostedNftId);
    }
  }
// Solidity 0.8.10
/**
 * @notice Calculates all the NFTs currently staken by
 *         an address
 *
 * @dev This is an auxiliary function to help with integration
 *      and is not used anywhere in the smart contract login
 *
 * @param _owner address to search staked tokens of
 * @return an array of token IDs of NFTs that are currently staken
 */
function tokensStakedByOwner(address _owner) external view returns (uint256[] memory) {
    // Cache the length of the staked tokens set for the owner
    uint256 stakedTokensLength = stakedTokens[_owner].length();

    // Create an empty array to store the result
    // Should be the same length as the staked tokens
    // set
    uint256[] memory tokenIds = new uint256[](stakedTokensLength);

    // Copy set values to array
    for (uint256 i = 0; i < stakedTokensLength; i++) {
      tokenIds[i] = stakedTokens[_owner].at(i);
    }

    // Return array result
    return tokenIds;
  }
// Solidity 0.8.10
/**
 * @notice Stake NFTs to start earning ERC-20
 *         token rewards
 *
 * The ERC-20 token rewards will be paid out
 * when the NFTs are unstaken
 *
 * @dev Sender must first approve this contract
 *      to transfer NFTs on his behalf and NFT
 *      ownership is transferred to this contract
 *      for the duration of the staking
 *
 * @param _tokenIds token IDs of NFTs to be staken
 */
function stake(uint256[] memory _tokenIds) public {
    // Ensure at least one token ID was sent
    require(_tokenIds.length > 0, "no token IDs sent");

    // Enumerate sent token IDs
    for (uint256 i = 0; i < _tokenIds.length; i++) {
      // Get token ID
      uint256 tokenId = _tokenIds[i];

      // Store NFT owner
      ownerOf[tokenId] = msg.sender;

      // Add NFT to owner staked tokens
      stakedTokens[msg.sender].add(tokenId);

      // Store staking time as block timestamp the
      // the transaction was confirmed in
      stakedAt[tokenId] = block.timestamp;

      // Transfer token to staking contract
      // Will fail if the user does not own the
      // token or has not approved the staking
      // contract for transferring tokens on his
      // behalf
      erc721.safeTransferFrom(msg.sender, address(this), tokenId, "");

      // Emit event
      emit Staked(msg.sender, tokenId, stakedAt[tokenId]);
    }
  }
// Solidity 0.8.4
// Helpful for UIs
function collateral_information(address collat_address) external view returns (CollateralInformation memory return_data){
        require(enabled_collaterals[collat_address], "Invalid collateral");

        // Get the index
        uint256 idx = collateralAddrToIdx[collat_address];
        
        return_data = CollateralInformation(
            idx, // [0]
            collateral_symbols[idx], // [1]
            collat_address, // [2]
            enabled_collaterals[collat_address], // [3]
            missing_decimals[idx], // [4]
            collateral_prices[idx], // [5]
            pool_ceilings[idx], // [6]
            mintPaused[idx], // [7]
            redeemPaused[idx], // [8]
            recollateralizePaused[idx], // [9]
            buyBackPaused[idx], // [10]
            minting_fee[idx], // [11]
            redemption_fee[idx], // [12]
            buyback_fee[idx], // [13]
            recollat_fee[idx] // [14]
        );
    }
// Solidity 0.8.4
// Returns the value of excess collateral (in E18) held globally, compared to what is needed to maintain the global collateral ratio
// Also has throttling to avoid dumps during large price movements
function buybackAvailableCollat() public view returns (uint256) {
        uint256 total_supply = FRAX.totalSupply();
        uint256 global_collateral_ratio = FRAX.global_collateral_ratio();
        uint256 global_collat_value = FRAX.globalCollateralValue();

        if (global_collateral_ratio > PRICE_PRECISION) global_collateral_ratio = PRICE_PRECISION; // Handles an overcollateralized contract with CR > 1
        uint256 required_collat_dollar_value_d18 = (total_supply.mul(global_collateral_ratio)).div(PRICE_PRECISION); // Calculates collateral needed to back each 1 FRAX with $1 of collateral at current collat ratio
        
        if (global_collat_value > required_collat_dollar_value_d18) {
            // Get the theoretical buyback amount
            uint256 theoretical_bbk_amt = global_collat_value.sub(required_collat_dollar_value_d18);

            // See how much has collateral has been issued this hour
            uint256 current_hr_bbk = bbkHourlyCum[curEpochHr()];

            // Account for the throttling
            return comboCalcBbkRct(current_hr_bbk, bbkMaxColE18OutPerHour, theoretical_bbk_amt);
        }
        else return 0;
    }