lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
/**
 * @notice Used to return all delegates with a given permission and module
 * @param _module Ethereum contract address of the module
 * @param _perm Permission flag
 * @return address[]
 */
function getAllDelegatesWithPerm(address _module, bytes32 _perm) external view returns(address[]) {
        uint256 counter = 0;
        uint256 i = 0;
        for (i = 0; i < allDelegates.length; i++) {
            if (perms[_module][allDelegates[i]][_perm]) {
                counter++;
            }
        }
        address[] memory allDelegatesWithPerm = new address[](counter);
        counter = 0;
        for (i = 0; i < allDelegates.length; i++) {
            if (perms[_module][allDelegates[i]][_perm]){
                allDelegatesWithPerm[counter] = allDelegates[i];
                counter++;
            }
        }
        return allDelegatesWithPerm;
    }
// Solidity 0.4.24
/**
 * @notice This function is used to validate the version submitted
 * @param _current Array holds the present version of ST
 * @param _new Array holds the latest version of the ST
 * @return bool
 */
function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) {
        bool[] memory _temp = new bool[](_current.length);
        uint8 counter = 0;
        for (uint8 i = 0; i < _current.length; i++) {
            if (_current[i] < _new[i])
                _temp[i] = true;
            else
                _temp[i] = false;
        }

        for (i = 0; i < _current.length; i++) {
            if (i == 0) {
                if (_current[i] <= _new[i])
                    if(_temp[0]) {
                        counter = counter + 3;
                        break;
                    } else
                        counter++;
                else
                    return false;
            } else {
                if (_temp[i-1])
                    counter++;
                else if (_current[i] <= _new[i])
                    counter++;
                else
                    return false;
            }
        }
        if (counter == _current.length)
            return true;
    }
// Solidity 0.4.24
/**
 * @notice Used to compare the lower bound with the latest version
 * @param _version1 Array holds the lower bound of the version
 * @param _version2 Array holds the latest version of the ST
 * @return bool
 */
function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
        require(_version1.length == _version2.length, "Input length mismatch");
        uint counter = 0;
        for (uint8 j = 0; j < _version1.length; j++) {
            if (_version1[j] == 0)
                counter ++;
        }
        if (counter != _version1.length) {
            counter = 0;
            for (uint8 i = 0; i < _version1.length; i++) {
                if (_version2[i] > _version1[i])
                    return true;
                else if (_version2[i] < _version1[i])
                    return false;
                else
                    counter++;
            }
            if (counter == _version1.length - 1)
                return true;
            else
                return false;
        } else
            return true;
    }
// Solidity 0.4.24
/**
 * @notice Function use to change the lower and upper bound of the compatible version st
 * @param _boundType Type of bound
 * @param _newVersion new version array
 */
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner {
        require(
            keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) ||
            keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")),
            "Must be a valid bound type"
        );
        require(_newVersion.length == 3);
        if (compatibleSTVersionRange[_boundType] != uint24(0)) { 
            uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);
            require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version");
        }
        compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);
        emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);
    }
// Solidity 0.4.24
/**
 * @notice Used to launch the Module with the help of factory
 * @return address Contract address of the Module
 */
function deploy(bytes /* _data */) external returns(address) {
        if(setupCost > 0)
            require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom due to insufficent Allowance provided");
        address permissionManager = new GeneralPermissionManager(msg.sender, address(polyToken));
        /*solium-disable-next-line security/no-block-members*/
        emit GenerateModuleFromFactory(address(permissionManager), getName(), address(this), msg.sender, setupCost, now);
        return permissionManager;
    }
// Solidity 0.4.24
/**
 * @notice Returns the instructions associated with the module
 */
function getInstructions() external view returns(string) {
        /*solium-disable-next-line max-len*/
        return "Add and remove permissions for the SecurityToken and associated modules. Permission types should be encoded as bytes32 values and attached using withPerm modifier to relevant functions. No initFunction required.";
    }
// Solidity 0.6.4
/**
 @notice Sets a new resource for handler contracts that use the IGenericHandler interface,
 and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
 @notice Only callable by an address that currently has the admin role.
 @param handlerAddress Address of handler resource will be set for.
 @param resourceID ResourceID to be used when making deposits.
 @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
 */
function adminSetGenericResource(
        address handlerAddress,
        bytes32 resourceID,
        address contractAddress,
        bytes4 depositFunctionSig,
        uint256 depositFunctionDepositerOffset,
        bytes4 executeFunctionSig
    ) external onlyAdmin {
        _resourceIDToHandlerAddress[resourceID] = handlerAddress;
        IGenericHandler handler = IGenericHandler(handlerAddress);
        handler.setResource(resourceID, contractAddress, depositFunctionSig, depositFunctionDepositerOffset, executeFunctionSig);
    }
// Solidity 0.6.4
/**
 @notice Initiates a transfer using a specified handler contract.
 @notice Only callable when Bridge is not paused.
 @param destinationChainID ID of chain deposit will be bridged to.
 @param resourceID ResourceID used to find address of handler to be used for deposit.
 @param data Additional data to be passed to specified handler.
 @notice Emits {Deposit} event.
 */
function deposit(uint8 destinationChainID, bytes32 resourceID, bytes calldata data) external payable whenNotPaused {
        require(msg.value == _fee, "Incorrect fee supplied");

        address handler = _resourceIDToHandlerAddress[resourceID];
        require(handler != address(0), "resourceID not mapped to handler");

        uint64 depositNonce = ++_depositCounts[destinationChainID];
        _depositRecords[depositNonce][destinationChainID] = data;

        IDepositExecute depositHandler = IDepositExecute(handler);
        depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);

        emit Deposit(destinationChainID, resourceID, depositNonce);
    }
// Solidity 0.6.4
/**
 @notice Executes a deposit proposal that is considered passed using a specified handler contract.
 @notice Only callable by relayers when Bridge is not paused.
 @param chainID ID of chain deposit originated from.
 @param depositNonce ID of deposited generated by origin Bridge contract.
 @param dataHash Hash of data originally provided when deposit was made.
 @notice Proposal must be past expiry threshold.
 @notice Emits {ProposalEvent} event with status {Cancelled}.
 */
function cancelProposal(uint8 chainID, uint64 depositNonce, bytes32 dataHash) public onlyAdminOrRelayer {
        uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
        Proposal storage proposal = _proposals[nonceAndID][dataHash];

        require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
        require(sub(block.number, proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");

        proposal._status = ProposalStatus.Cancelled;
        emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);

    }
// Solidity 0.6.4
/**
 @notice Executes a deposit proposal that is considered passed using a specified handler contract.
 @notice Only callable by relayers when Bridge is not paused.
 @param chainID ID of chain deposit originated from.
 @param resourceID ResourceID to be used when making deposits.
 @param depositNonce ID of deposited generated by origin Bridge contract.
 @param data Data originally provided when deposit was made.
 @notice Proposal must have Passed status.
 @notice Hash of {data} must equal proposal's {dataHash}.
 @notice Emits {ProposalEvent} event with status {Executed}.
 */
function executeProposal(uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID) external onlyRelayers whenNotPaused {
        address handler = _resourceIDToHandlerAddress[resourceID];
        uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
        bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
        Proposal storage proposal = _proposals[nonceAndID][dataHash];

        require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
        require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
        require(dataHash == proposal._dataHash, "data doesn't match datahash");

        proposal._status = ProposalStatus.Executed;

        IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
        depositHandler.executeProposal(proposal._resourceID, data);

        emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
    }
// Solidity 0.7.6
/*********************
 * Fallback Function *
 *********************/
fallback()
        external
    {
        (bool success, bytes memory returndata) = Lib_SafeExecutionManagerWrapper.safeDELEGATECALL(
            gasleft(),
            getImplementation(),
            msg.data
        );

        if (success) {
            assembly {
                return(add(returndata, 0x20), mload(returndata))
            }
        } else {
            Lib_SafeExecutionManagerWrapper.safeREVERT(
                string(returndata)
            );
        }
    }
// Solidity 0.7.6
/**
 * Recovers a signed address given a message and signature.
 * @param _message Message that was originally signed.
 * @param _isEthSignedMessage Whether or not the user used the `Ethereum Signed Message` prefix.
 * @param _v Signature `v` parameter.
 * @param _r Signature `r` parameter.
 * @param _s Signature `s` parameter.
 * @return _sender Signer address.
 */
function recover(
        bytes memory _message,
        bool _isEthSignedMessage,
        uint8 _v,
        bytes32 _r,
        bytes32 _s
    )
        internal
        pure
        returns (
            address _sender
        )
    {
        bytes32 messageHash = getMessageHash(_message, _isEthSignedMessage);

        return ecrecover(
            messageHash,
            _v + 27,
            _r,
            _s
        );
    }
// Solidity 0.7.6
/**
 * Initializes the whitelist.
 * @param _owner Address of the owner for this contract.
 * @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
 */
function initialize(
        address _owner,
        bool _allowArbitraryDeployment
    )
        override
        public
    {
        bool initialized = Lib_Bytes32Utils.toBool(
            Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED)
        );

        if (initialized == true) {
            return;
        }

        Lib_SafeExecutionManagerWrapper.safeSSTORE(
            KEY_INITIALIZED,
            Lib_Bytes32Utils.fromBool(true)
        );
        Lib_SafeExecutionManagerWrapper.safeSSTORE(
            KEY_OWNER,
            Lib_Bytes32Utils.fromAddress(_owner)
        );
        Lib_SafeExecutionManagerWrapper.safeSSTORE(
            KEY_ALLOW_ARBITRARY_DEPLOYMENT,
            Lib_Bytes32Utils.fromBool(_allowArbitraryDeployment)
        );
    }
// Solidity 0.7.6
/**
 * Checks whether an address is allowed to deploy contracts.
 * @param _deployer Address to check.
 * @return _allowed Whether or not the address can deploy contracts.
 */
function isDeployerAllowed(
        address _deployer
    )
        override
        public
        returns (
            bool _allowed
        )
    {
        bool initialized = Lib_Bytes32Utils.toBool(
            Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_INITIALIZED)
        );

        if (initialized == false) {
            return true;
        }

        bool allowArbitraryDeployment = Lib_Bytes32Utils.toBool(
            Lib_SafeExecutionManagerWrapper.safeSLOAD(KEY_ALLOW_ARBITRARY_DEPLOYMENT)
        );

        if (allowArbitraryDeployment == true) {
            return true;
        }

        bool isWhitelisted = Lib_Bytes32Utils.toBool(
            Lib_SafeExecutionManagerWrapper.safeSLOAD(
                Lib_Bytes32Utils.fromAddress(_deployer)
            )
        );

        return isWhitelisted;        
    }
// Solidity 0.8.0
/**
 * @dev Mints `quantity` tokens and transfers them to `to`.
 *
 * Requirements:
 *
 * - `to` cannot be the zero address.
 * - `quantity` cannot be larger than the max batch size.
 *
 * Emits a {Transfer} event.
 */
function _safeMint(
        address to,
        uint256 quantity,
        bytes memory _data
    ) internal {
        uint256 startTokenId = currentIndex;
        require(to != address(0), 'ERC721A: mint to the zero address');
        // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
        require(!_exists(startTokenId), 'ERC721A: token already minted');
        require(quantity > 0, 'ERC721A: quantity must be greater 0');

        _beforeTokenTransfers(address(0), to, startTokenId, quantity);

        AddressData memory addressData = _addressData[to];
        _addressData[to] = AddressData(
            addressData.balance + uint128(quantity),
            addressData.numberMinted + uint128(quantity)
        );
        _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));

        uint256 updatedIndex = startTokenId;

        for (uint256 i = 0; i < quantity; i++) {
            emit Transfer(address(0), to, updatedIndex);
            require(
                _checkOnERC721Received(address(0), to, updatedIndex, _data),
                'ERC721A: transfer to non ERC721Receiver implementer'
            );
            updatedIndex++;
        }

      currentIndex = updatedIndex;
        _afterTokenTransfers(address(0), to, startTokenId, quantity);
    }
// Solidity 0.8.4
/** Initiate the start of a mint. This action burns $CHEDDAR, as the intent of committing is that you cannot back out once you've started.
 * This will add users into the pending queue, to be revealed after a random seed is generated and assigned to the commit id this
 * commit was added to. */
function mintCommit(uint256 amount, bool stake) external whenNotPaused nonReentrant {
    require(allowCommits, "adding commits disallowed");
    require(tx.origin == _msgSender(), "Only EOA");
    require(_pendingCommitId[_msgSender()] == 0, "Already have pending mints");
    uint16 minted = houseNFT.minted();
    uint256 maxTokens = houseNFT.getMaxTokens();
    require(minted + pendingMintAmt + amount <= maxTokens, "All tokens minted");
    require(amount > 0 && amount <= 10, "Invalid mint amount");

    uint256 totalCheddarCost = 0;
    // Loop through the amount of 
    for (uint i = 1; i <= amount; i++) {
      totalCheddarCost += mintCost(minted + pendingMintAmt + i, maxTokens);
    }
    if (totalCheddarCost > 0) {
      cheddarToken.burn(_msgSender(), totalCheddarCost);
      cheddarToken.updateOriginAccess();
    }
    uint16 amt = uint16(amount);
    _mintCommits[_msgSender()][randomizer.commitId()] = MintCommit(stake, amt);
    _pendingCommitId[_msgSender()] = randomizer.commitId();
    pendingMintAmt += amt;
    emit MintCommitted(_msgSender(), amount);
  }
// Solidity 0.8.4
/**
 * the first 25% are 80000 $CHEDDAR
 * the next 50% are 160000 $CHEDDAR
 * the next 25% are 320000 $WOOL
 * @param tokenId the ID to check the cost of to mint
 * @return the cost of the given token ID
 */
function mintCost(uint256 tokenId, uint256 maxTokens) public pure returns (uint256) {
    if (tokenId <= maxTokens / 4) return 80000 ether;
    if (tokenId <= maxTokens * 3 / 4) return 160000 ether;
    return 320000 ether;
  }
// Solidity 0.8.4
/**
 * @param seed a random value to select a recipient from
 * @return the address of the recipient (either the minter or the Cat thief's owner)
 */
function selectRecipient(uint256 seed) internal view returns (address) {
    if (((seed >> 245) % 8) != 0) return _msgSender(); // top 8 bits haven't been used
    address thief = habitat.randomCrazyCatOwner(seed >> 144); // 144 bits reserved for trait selection
    if (thief == address(0x0)) return _msgSender();
    return thief;
  }
// Solidity 0.6.8
/**
 * @notice Sets the address of the Fee wallet
 *
 * @dev Trade and Withdraw fees will accrue in the `_balancesInPips` mappings for this wallet
 *
 * @param newFeeWallet The new Fee wallet. Must be different from the current one
 */
function setFeeWallet(address newFeeWallet) external onlyAdmin {
    require(newFeeWallet != address(0x0), 'Invalid wallet address');
    require(
      newFeeWallet != _feeWallet,
      'Must be different from current fee wallet'
    );

    address oldFeeWallet = _feeWallet;
    _feeWallet = newFeeWallet;

    emit FeeWalletChanged(oldFeeWallet, newFeeWallet);
  }
// Solidity 0.6.8
/**
 * @notice Load a wallet's balance by asset address, in asset units
 *
 * @param wallet The wallet address to load the balance for. Can be different from `msg.sender`
 * @param assetAddress The asset address to load the wallet's balance for
 *
 * @return The quantity denominated in asset units of asset at `assetAddress` currently
 * deposited by `wallet`
 */
function loadBalanceInAssetUnitsByAddress(
    address wallet,
    address assetAddress
  ) external view returns (uint256) {
    require(wallet != address(0x0), 'Invalid wallet address');

    Structs.Asset memory asset = _assetRegistry.loadAssetByAddress(
      assetAddress
    );
    return
      AssetUnitConversions.pipsToAssetUnits(
        _balancesInPips[wallet][assetAddress],
        asset.decimals
      );
  }
// Solidity 0.6.8
/**
 * @notice Deposit `IERC20` compliant tokens
 *
 * @param assetSymbol The case-sensitive symbol string for the token
 * @param quantityInAssetUnits The quantity to deposit. The sending wallet must first call the `approve` method on
 * the token contract for at least this quantity first
 */
function depositTokenBySymbol(
    string calldata assetSymbol,
    uint256 quantityInAssetUnits
  ) external {
    IERC20 tokenAddress = IERC20(
      _assetRegistry
        .loadAssetBySymbol(assetSymbol, getCurrentTimestampInMs())
        .assetAddress
    );
    require(
      address(tokenAddress) != address(0x0),
      'Use depositEther to deposit ETH'
    );

    deposit(msg.sender, address(tokenAddress), quantityInAssetUnits);
  }
// Solidity 0.6.8
/**
 * @notice Invalidate all order nonces with a timestampInMs lower than the one provided
 *
 * @param nonce A Version 1 UUID. After calling and once the Chain Propagation Period has elapsed,
 * `executeTrade` will reject order nonces from this wallet with a timestampInMs component lower than
 * the one provided
 */
function invalidateOrderNonce(uint128 nonce) external {
    uint64 timestampInMs = UUID.getTimestampInMsFromUuidV1(nonce);
    // Enforce a maximum skew for invalidating nonce timestamps in the future so the user doesn't
    // lock their wallet from trades indefinitely
    require(
      timestampInMs < getOneDayFromNowInMs(),
      'Nonce timestamp too far in future'
    );

    if (_nonceInvalidations[msg.sender].exists) {
      require(
        _nonceInvalidations[msg.sender].timestampInMs < timestampInMs,
        'Nonce timestamp already invalidated'
      );
      require(
        _nonceInvalidations[msg.sender].effectiveBlockNumber <= block.number,
        'Previous invalidation awaiting chain propagation'
      );
    }

    // Changing the Chain Propagation Period will not affect the effectiveBlockNumber for this invalidation
    uint256 effectiveBlockNumber = block.number + _chainPropagationPeriod;
    _nonceInvalidations[msg.sender] = NonceInvalidation(
      true,
      timestampInMs,
      effectiveBlockNumber
    );

    emit OrderNonceInvalidated(
      msg.sender,
      nonce,
      timestampInMs,
      effectiveBlockNumber
    );
  }
// Solidity 0.6.8
/**
 * @notice Settles a user withdrawal submitted off-chain. Calls restricted to currently whitelisted Dispatcher wallet
 *
 * @param withdrawal A `Structs.Withdrawal` struct encoding the parameters of the withdrawal
 */
function withdraw(Structs.Withdrawal memory withdrawal)
    public
    override
    onlyDispatcher
  {
    // Validations
    require(!isWalletExitFinalized(withdrawal.walletAddress), 'Wallet exited');
    require(
      getFeeBasisPoints(withdrawal.gasFeeInPips, withdrawal.quantityInPips) <=
        _maxWithdrawalFeeBasisPoints,
      'Excessive withdrawal fee'
    );
    bytes32 withdrawalHash = validateWithdrawalSignature(withdrawal);
    require(
      !_completedWithdrawalHashes[withdrawalHash],
      'Hash already withdrawn'
    );

    // If withdrawal is by asset symbol (most common) then resolve to asset address
    Structs.Asset memory asset = withdrawal.withdrawalType ==
      Enums.WithdrawalType.BySymbol
      ? _assetRegistry.loadAssetBySymbol(
        withdrawal.assetSymbol,
        UUID.getTimestampInMsFromUuidV1(withdrawal.nonce)
      )
      : _assetRegistry.loadAssetByAddress(withdrawal.assetAddress);

    // SafeMath reverts if balance is overdrawn
    uint64 netAssetQuantityInPips = withdrawal.quantityInPips.sub(
      withdrawal.gasFeeInPips
    );
    uint256 netAssetQuantityInAssetUnits = AssetUnitConversions
      .pipsToAssetUnits(netAssetQuantityInPips, asset.decimals);
    uint64 newExchangeBalanceInPips = _balancesInPips[withdrawal
      .walletAddress][asset.assetAddress]
      .sub(withdrawal.quantityInPips);
    uint256 newExchangeBalanceInAssetUnits = AssetUnitConversions
      .pipsToAssetUnits(newExchangeBalanceInPips, asset.decimals);

    _balancesInPips[withdrawal.walletAddress][asset
      .assetAddress] = newExchangeBalanceInPips;
    _balancesInPips[_feeWallet][asset
      .assetAddress] = _balancesInPips[_feeWallet][asset.assetAddress].add(
      withdrawal.gasFeeInPips
    );

    ICustodian(_custodian).withdraw(
      withdrawal.walletAddress,
      asset.assetAddress,
      netAssetQuantityInAssetUnits
    );

    _completedWithdrawalHashes[withdrawalHash] = true;

    emit Withdrawn(
      withdrawal.walletAddress,
      asset.assetAddress,
      asset.symbol,
      withdrawal.quantityInPips,
      newExchangeBalanceInPips,
      newExchangeBalanceInAssetUnits
    );
  }