lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
/**
 * @notice Queries a value at a defined checkpoint
 * @param _checkpoints is array of Checkpoint objects
 * @param _checkpointId is the Checkpoint ID to query
 * @param _currentValue is the Current value of checkpoint
 * @return uint256
 */
function getValueAt(Checkpoint[] storage _checkpoints, uint256 _checkpointId, uint256 _currentValue) public view returns(uint256) {
        //Checkpoint id 0 is when the token is first created - everyone has a zero balance
        if (_checkpointId == 0) {
            return 0;
        }
        if (_checkpoints.length == 0) {
            return _currentValue;
        }
        if (_checkpoints[0].checkpointId >= _checkpointId) {
            return _checkpoints[0].value;
        }
        if (_checkpoints[_checkpoints.length - 1].checkpointId < _checkpointId) {
            return _currentValue;
        }
        if (_checkpoints[_checkpoints.length - 1].checkpointId == _checkpointId) {
            return _checkpoints[_checkpoints.length - 1].value;
        }
        uint256 min = 0;
        uint256 max = _checkpoints.length - 1;
        while (max > min) {
            uint256 mid = (max + min) / 2;
            if (_checkpoints[mid].checkpointId == _checkpointId) {
                max = mid;
                break;
            }
            if (_checkpoints[mid].checkpointId < _checkpointId) {
                min = mid + 1;
            } else {
                max = mid;
            }
        }
        return _checkpoints[max].value;
    }
// Solidity 0.4.24
/**
 * @notice Stores the changes to the checkpoint objects
 * @param _checkpoints is the affected checkpoint object array
 * @param _newValue is the new value that needs to be stored
 */
function adjustCheckpoints(TokenLib.Checkpoint[] storage _checkpoints, uint256 _newValue, uint256 _currentCheckpointId) public {
        //No checkpoints set yet
        if (_currentCheckpointId == 0) {
            return;
        }
        //No new checkpoints since last update
        if ((_checkpoints.length > 0) && (_checkpoints[_checkpoints.length - 1].checkpointId == _currentCheckpointId)) {
            return;
        }
        //New checkpoint, so record balance
        _checkpoints.push(
            TokenLib.Checkpoint({
                checkpointId: _currentCheckpointId,
                value: _newValue
            })
        );
    }
// Solidity 0.4.24
/**
 * @notice Keeps track of the number of non-zero token holders
 * @param _investorData Date releated to investor metrics
 * @param _from Sender of transfer
 * @param _to Receiver of transfer
 * @param _value Value of transfer
 * @param _balanceTo Balance of the _to address
 * @param _balanceFrom Balance of the _from address
 */
function adjustInvestorCount(
        InvestorDataStorage storage _investorData,
        address _from,
        address _to,
        uint256 _value,
        uint256 _balanceTo,
        uint256 _balanceFrom
        ) public  {
        if ((_value == 0) || (_from == _to)) {
            return;
        }
        // Check whether receiver is a new token holder
        if ((_balanceTo == 0) && (_to != address(0))) {
            _investorData.investorCount = (_investorData.investorCount).add(1);
        }
        // Check whether sender is moving all of their tokens
        if (_value == _balanceFrom) {
            _investorData.investorCount = (_investorData.investorCount).sub(1);
        }
        //Also adjust investor list
        if (!_investorData.investorListed[_to] && (_to != address(0))) {
            _investorData.investors.push(_to);
            _investorData.investorListed[_to] = true;
        }

    }
// Solidity 0.4.24
/**
 * @notice Attachs a module to the SecurityToken
 * @dev  E.G.: On deployment (through the STR) ST gets a TransferManager module attached to it
 * @dev to control restrictions on transfers.
 * @param _moduleFactory is the address of the module factory to be added
 * @param _data is data packed into bytes used to further configure the module (See STO usage)
 * @param _maxCost max amount of POLY willing to pay to the module.
 * @param _budget max amount of ongoing POLY willing to assign to the module.
 */
function addModule(
        address _moduleFactory,
        bytes _data,
        uint256 _maxCost,
        uint256 _budget
    ) external onlyOwner nonReentrant {
        //Check that the module factory exists in the ModuleRegistry - will throw otherwise
        IModuleRegistry(moduleRegistry).useModule(_moduleFactory);
        IModuleFactory moduleFactory = IModuleFactory(_moduleFactory);
        uint8[] memory moduleTypes = moduleFactory.getTypes();
        uint256 moduleCost = moduleFactory.getSetupCost();
        require(moduleCost <= _maxCost, "Invalid cost");
        //Approve fee for module
        ERC20(polyToken).approve(_moduleFactory, moduleCost);
        //Creates instance of module from factory
        address module = moduleFactory.deploy(_data);
        require(modulesToData[module].module == address(0), "Module exists");
        //Approve ongoing budget
        ERC20(polyToken).approve(module, _budget);
        //Add to SecurityToken module map
        bytes32 moduleName = moduleFactory.getName();
        uint256[] memory moduleIndexes = new uint256[](moduleTypes.length);
        uint256 i;
        for (i = 0; i < moduleTypes.length; i++) {
            moduleIndexes[i] = modules[moduleTypes[i]].length;
            modules[moduleTypes[i]].push(module);
        }
        modulesToData[module] = TokenLib.ModuleData(
            moduleName, module, _moduleFactory, false, moduleTypes, moduleIndexes, names[moduleName].length
        );
        names[moduleName].push(module);
        //Emit log event
        /*solium-disable-next-line security/no-block-members*/
        emit ModuleAdded(moduleTypes, moduleName, _moduleFactory, module, moduleCost, _budget, now);
    }
// Solidity 0.4.24
/**
 * @notice Removes a module attached to the SecurityToken
 * @param _module address of module to unarchive
 */
function removeModule(address _module) external onlyOwner {
        require(modulesToData[_module].isArchived, "Not archived");
        require(modulesToData[_module].module != address(0), "Module missing");
        /*solium-disable-next-line security/no-block-members*/
        emit ModuleRemoved(modulesToData[_module].moduleTypes, _module, now);
        // Remove from module type list
        uint8[] memory moduleTypes = modulesToData[_module].moduleTypes;
        for (uint256 i = 0; i < moduleTypes.length; i++) {
            _removeModuleWithIndex(moduleTypes[i], modulesToData[_module].moduleIndexes[i]);
            /* modulesToData[_module].moduleType[moduleTypes[i]] = false; */
        }
        // Remove from module names list
        uint256 index = modulesToData[_module].nameIndex;
        bytes32 name = modulesToData[_module].name;
        uint256 length = names[name].length;
        names[name][index] = names[name][length - 1];
        names[name].length = length - 1;
        if ((length - 1) != index) {
            modulesToData[names[name][index]].nameIndex = index;
        }
        // Remove from modulesToData
        delete modulesToData[_module];
    }
// Solidity 0.4.24
/**
 * @notice Internal - Removes a module attached to the SecurityToken by index
 */
function _removeModuleWithIndex(uint8 _type, uint256 _index) internal {
        uint256 length = modules[_type].length;
        modules[_type][_index] = modules[_type][length - 1];
        modules[_type].length = length - 1;

        if ((length - 1) != _index) {
            //Need to find index of _type in moduleTypes of module we are moving
            uint8[] memory newTypes = modulesToData[modules[_type][_index]].moduleTypes;
            for (uint256 i = 0; i < newTypes.length; i++) {
                if (newTypes[i] == _type) {
                    modulesToData[modules[_type][_index]].moduleIndexes[i] = _index;
                }
            }
        }
    }
// Solidity 0.4.24
/**
 
 * @notice allows owner to increase/decrease POLY approval of one of the modules
 * @param _module module address
 * @param _change change in allowance
 * @param _increase true if budget has to be increased, false if decrease
 */
function changeModuleBudget(address _module, uint256 _change, bool _increase) external onlyOwner {
        require(modulesToData[_module].module != address(0), "Module missing");
        uint256 currentAllowance = IERC20(polyToken).allowance(address(this), _module);
        uint256 newAllowance;
        if (_increase) {
            require(IERC20(polyToken).increaseApproval(_module, _change), "IncreaseApproval fail");
            newAllowance = currentAllowance.add(_change);
        } else {
            require(IERC20(polyToken).decreaseApproval(_module, _change), "Insufficient allowance");
            newAllowance = currentAllowance.sub(_change);
        }
        emit ModuleBudgetChanged(modulesToData[_module].moduleTypes, _module, currentAllowance, newAllowance);
    }
// Solidity 0.4.24
/**
 * @notice returns an array of investors at a given checkpoint
 * NB - this length may differ from investorCount as it contains all investors that ever held tokens
 * @param _checkpointId Checkpoint id at which investor list is to be populated
 * @return list of investors
 */
function getInvestorsAt(uint256 _checkpointId) external view returns(address[]) {
        uint256 count = 0;
        uint256 i;
        for (i = 0; i < investorData.investors.length; i++) {
            if (balanceOfAt(investorData.investors[i], _checkpointId) > 0) {
                count++;
            }
        }
        address[] memory investors = new address[](count);
        count = 0;
        for (i = 0; i < investorData.investors.length; i++) {
            if (balanceOfAt(investorData.investors[i], _checkpointId) > 0) {
                investors[count] = investorData.investors[i];
                count++;
            }
        }
        return investors;
    }
// Solidity 0.4.24
/**
 * @notice generates subset of investors
 * NB - can be used in batches if investor list is large
 * @param _start Position of investor to start iteration from
 * @param _end Position of investor to stop iteration at
 * @return list of investors
 */
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[]) {
        require(_end <= investorData.investors.length, "Invalid end");
        address[] memory investors = new address[](_end.sub(_start));
        uint256 index = 0;
        for (uint256 i = _start; i < _end; i++) {
            investors[index] = investorData.investors[i];
            index++;
        }
        return investors;
    }
// Solidity 0.4.24
/**
 * @notice Updates internal variables when performing a transfer
 * @param _from sender of transfer
 * @param _to receiver of transfer
 * @param _value value of transfer
 * @param _data data to indicate validation
 * @return bool success
 */
function _updateTransfer(address _from, address _to, uint256 _value, bytes _data) internal nonReentrant returns(bool) {
        // NB - the ordering in this function implies the following:
        //  - investor counts are updated before transfer managers are called - i.e. transfer managers will see
        //investor counts including the current transfer.
        //  - checkpoints are updated after the transfer managers are called. This allows TMs to create
        //checkpoints as though they have been created before the current transactions,
        //  - to avoid the situation where a transfer manager transfers tokens, and this function is called recursively,
        //the function is marked as nonReentrant. This means that no TM can transfer (or mint / burn) tokens.
        _adjustInvestorCount(_from, _to, _value);
        bool verified = _verifyTransfer(_from, _to, _value, _data, true);
        _adjustBalanceCheckpoints(_from);
        _adjustBalanceCheckpoints(_to);
        return verified;
    }
// Solidity 0.4.24
/**
 * @notice Validate transfer with TransferManager module if it exists
 * @dev TransferManager module has a key of 2
 * @dev _isTransfer boolean flag is the deciding factor for whether the
 * state variables gets modified or not within the different modules. i.e isTransfer = true
 * leads to change in the modules environment otherwise _verifyTransfer() works as a read-only
 * function (no change in the state).
 * @param _from sender of transfer
 * @param _to receiver of transfer
 * @param _value value of transfer
 * @param _data data to indicate validation
 * @param _isTransfer whether transfer is being executed
 * @return bool
 */
function _verifyTransfer(
        address _from,
        address _to,
        uint256 _value,
        bytes _data,
        bool _isTransfer
    ) internal checkGranularity(_value) returns (bool) {
        if (!transfersFrozen) {
            bool isInvalid = false;
            bool isValid = false;
            bool isForceValid = false;
            bool unarchived = false;
            address module;
            for (uint256 i = 0; i < modules[TRANSFER_KEY].length; i++) {
                module = modules[TRANSFER_KEY][i];
                if (!modulesToData[module].isArchived) {
                    unarchived = true;
                    ITransferManager.Result valid = ITransferManager(module).verifyTransfer(_from, _to, _value, _data, _isTransfer);
                    if (valid == ITransferManager.Result.INVALID) {
                        isInvalid = true;
                    } else if (valid == ITransferManager.Result.VALID) {
                        isValid = true;
                    } else if (valid == ITransferManager.Result.FORCE_VALID) {
                        isForceValid = true;
                    }
                }
            }
            // If no unarchived modules, return true by default
            return unarchived ? (isForceValid ? true : (isInvalid ? false : isValid)) : true;
        }
        return false;
    }
// Solidity 0.4.24
/**
 * @notice mints new tokens and assigns them to the target _investor.
 * @dev Can only be called by the issuer or STO attached to the token
 * @param _investor Address where the minted tokens will be delivered
 * @param _value Number of tokens be minted
 * @param _data data to indicate validation
 * @return success
 */
function mintWithData(
        address _investor,
        uint256 _value,
        bytes _data
        ) public onlyModuleOrOwner(MINT_KEY) isMintingAllowed() returns (bool success) {
        require(_investor != address(0), "Investor is 0");
        require(_updateTransfer(address(0), _investor, _value, _data), "Transfer invalid");
        _adjustTotalSupplyCheckpoints();
        totalSupply_ = totalSupply_.add(_value);
        balances[_investor] = balances[_investor].add(_value);
        emit Minted(_investor, _value);
        emit Transfer(address(0), _investor, _value);
        return true;
    }
// Solidity 0.4.24
/**
 * @notice Mints new tokens and assigns them to the target _investor.
 * @dev Can only be called by the issuer or STO attached to the token.
 * @param _investors A list of addresses to whom the minted tokens will be dilivered
 * @param _values A list of number of tokens get minted and transfer to corresponding address of the investor from _investor[] list
 * @return success
 */
function mintMulti(address[] _investors, uint256[] _values) external returns (bool success) {
        require(_investors.length == _values.length, "Incorrect inputs");
        for (uint256 i = 0; i < _investors.length; i++) {
            mint(_investors[i], _values[i]);
        }
        return true;
    }
// Solidity 0.4.24
/**
 * @notice Validate permissions with PermissionManager if it exists, If no Permission return false
 * @dev Note that IModule withPerm will allow ST owner all permissions anyway
 * @dev this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
 * @param _delegate address of delegate
 * @param _module address of PermissionManager module
 * @param _perm the permissions
 * @return success
 */
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool) {
        for (uint256 i = 0; i < modules[PERMISSION_KEY].length; i++) {
            if (!modulesToData[modules[PERMISSION_KEY][i]].isArchived)
                return TokenLib.checkPermission(modules[PERMISSION_KEY], _delegate, _module, _perm);
        }
        return false;
    }
// Solidity 0.4.24
/**
 * @notice Used by a controller to execute a forced transfer
 * @param _from address from which to take tokens
 * @param _to address where to send tokens
 * @param _value amount of tokens to transfer
 * @param _data data to indicate validation
 * @param _log data attached to the transfer by controller to emit in event
 */
function forceTransfer(address _from, address _to, uint256 _value, bytes _data, bytes _log) public onlyController {
        require(_to != address(0));
        require(_value <= balances[_from]);
        bool verified = _updateTransfer(_from, _to, _value, _data);
        balances[_from] = balances[_from].sub(_value);
        balances[_to] = balances[_to].add(_value);
        emit ForceTransfer(msg.sender, _from, _to, _value, verified, _log);
        emit Transfer(_from, _to, _value);
    }
// Solidity 0.4.24
/**
 * @notice deploys the token and adds default modules like the GeneralTransferManager.
 * Future versions of the proxy can attach different modules or pass different parameters.
 */
function deployToken(
        string _name,
        string _symbol,
        uint8 _decimals,
        string _tokenDetails,
        address _issuer,
        bool _divisible,
        address _polymathRegistry
        ) external returns (address) {
        address newSecurityTokenAddress = new SecurityToken(
            _name,
            _symbol,
            _decimals,
            _divisible ? 1 : uint256(10)**_decimals,
            _tokenDetails,
            _polymathRegistry
        );
        SecurityToken(newSecurityTokenAddress).addModule(transferManagerFactory, "", 0, 0);
        SecurityToken(newSecurityTokenAddress).transferOwnership(_issuer);
        return newSecurityTokenAddress;
    }
// Solidity 0.8.7
/// @dev See {ILairControls.claimBloodBags}
function claimBloodBags(address sender, uint16 tokenId)
        external
        override
        onlyControllers
        returns (uint256 owed)
    {
        uint8 score = _predatorScoreForVampire(tokenId);
        VampireStake memory stake = scoreStakingMap[score][
            stakeIndices[tokenId]
        ];
        require(sender == stake.owner, "NOT_OWNER_OR_NOT_STAKED");

        // Calculate and sets amount of bloodbags owed (this is returned by the fn)
        uint256 _bloodbagPerPredatorScore = bloodbagPerPredatorScore;
        owed =
            score *
            (_bloodbagPerPredatorScore -
                stake.bloodbagPerPredatorScoreWhenStaked);

        // Resets the vampire staking info
        scoreStakingMap[score][stakeIndices[tokenId]] = VampireStake({
            owner: sender,
            tokenId: tokenId,
            bloodbagPerPredatorScoreWhenStaked: uint80(
                _bloodbagPerPredatorScore
            )
        });

        // Logs an event with the blood claiming info
        emit BloodBagClaimed(sender, tokenId, owed);

        // <- Controller is supposed to transfer $BLOODBAGs
    }
// Solidity 0.8.7
/// ==== Migration
function migrate(
        uint16[] calldata vampires,
        uint8[] calldata predatorIndices
    ) external nonReentrant {
        require(
            vampires.length == predatorIndices.length,
            "ARRAYS_SHOULD_HAVE_SAME_SIZE"
        );

        uint16 tokenId;
        uint8 predatorIndex;
        for (uint256 i = 0; i < vampires.length; i++) {
            tokenId = vampires[i];
            predatorIndex = predatorIndices[i];
            uint256 idx = legacyLair.stakeIndices(tokenId);
            (address owner, , ) = legacyLair.scoreStakingMap(
                predatorIndex,
                idx
            );
            require(owner == _msgSender(), "NOT_OWNER");
            legacyLair.unstakeVampire(_msgSender(), tokenId);
            _stakeVampire(_msgSender(), tokenId);
            vgame.transferFrom(address(legacyLair), address(this), tokenId);
        }
        bloodbag.mint(_msgSender(), vampires.length * 10 ether);
    }
// Solidity 0.4.25
//Accrual of referral bonuses to the participant
function setRefererBonus(address addr, uint256 amount, uint256 level_percent, uint256 level_num) private {
		if (addr.notZero()) {
			uint256 revenue = amount.mul(level_percent).div(100);

			if (!checkInvestor(addr)) {
				createInvestor(addr, address(0));
			}

			investors[addr].referals_profit = investors[addr].referals_profit.add(revenue);
			investors[addr].referals_profit_balance = investors[addr].referals_profit_balance.add(revenue);
			emit RefererBonus(msg.sender, addr, amount, revenue, level_num);
		}
	}
// Solidity 0.4.25
//Accrual of referral bonuses to participants
function setAllRefererBonus(address addr, uint256 amount) private {

		address ref_addr_level_1 = investors[addr].referer;
		address ref_addr_level_2 = investors[ref_addr_level_1].referer;
		address ref_addr_level_3 = investors[ref_addr_level_2].referer;

		setRefererBonus (ref_addr_level_1, amount, ref_bonus_level_1, 1);
		setRefererBonus (ref_addr_level_2, amount, ref_bonus_level_2, 2);
		setRefererBonus (ref_addr_level_3, amount, ref_bonus_level_3, 3);
	}
// Solidity 0.4.25
//Get the number of dividends
function calcDivedents (address addr) public view returns (uint256) {
		uint256 current_perc = 0;
		if (address(this).balance < 2000 ether) {
			current_perc = dividends_perc_before_2000eth;
		}
		else {
			current_perc = dividends_perc_after_2000eth;
		}

		return investors[addr].investment.mul(current_perc).div(1000).mul(now.sub(investors[addr].investment_time)).div(1 days);
	}
// Solidity 0.4.25
//Income payment
function withdraw_revenue(address addr) private {
		uint256 withdraw_amount = calcDivedents(addr);
		
		if (check_x2_profit(addr,withdraw_amount) == true) {
		   withdraw_amount = 0; 
		}
		
		if (withdraw_amount > 0) {
		   investors[addr].investment_profit = investors[addr].investment_profit.add(withdraw_amount); 
		}
		
		withdraw_amount = withdraw_amount.add(investors[addr].investment_profit_balance).add(investors[addr].referals_profit_balance).add(investors[addr].cashback_profit_balance);
		

		if (withdraw_amount > 0) {
			clear_balance(addr);
			all_payments = all_payments.add(withdraw_amount);
			emit NewWithdraw(addr, withdraw_amount);
			emit ChangeBalance(address(this).balance.sub(withdraw_amount));
			addr.transfer(withdraw_amount);
		}
	}
// Solidity 0.4.25
//Checking the x2 profit
function check_x2_profit(address addr, uint256 dividends) private returns(bool) {
		if (investors[addr].investment_profit.add(dividends) > investors[addr].investment.mul(2)) {
		    investors[addr].investment_profit_balance = investors[addr].investment.mul(2).sub(investors[addr].investment_profit);
			investors[addr].investment = 0;
			investors[addr].investment_profit = 0;
			investors[addr].investment_first_time_in_day = 0;
			investors[addr].investment_time = 0;
			return true;
		}
		else {
		    return false;
		}
	}