lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.18
/**
 * Computes the amount of QSP that should be issued for the given transaction.
 * Contribution tiers are filled up in the order 3, 2, 1, 4.
 * @param addr      The wallet address of the contributor
 * @param amount    Amount of wei for payment
 */
function computeTokenAmount(address addr, uint amount) internal
        returns (uint){
        require(amount > 0);
        uint r3 = cap3[addr].sub(contributed3[addr]);
        uint r2 = cap2[addr].sub(contributed2[addr]);
        uint r1 = cap1[addr].sub(contributed1[addr]);
        uint r4 = cap4[addr].sub(contributed4[addr]);
        uint numTokens = 0;
        // cannot contribute more than the remaining sum
        assert(amount <= r3.add(r2).add(r1).add(r4));
        // Compute tokens for tier 3
        if(r3 > 0){
            if(amount <= r3){
                contributed3[addr] = contributed3[addr].add(amount);
                return rate3.mul(amount);
            }
            else{
                numTokens = rate3.mul(r3);
                amount = amount.sub(r3);
                contributed3[addr] = cap3[addr];
            }
        }
        // Compute tokens for tier 2
        if(r2 > 0){
            if(amount <= r2){
                contributed2[addr] = contributed2[addr].add(amount);
                return numTokens.add(rate2.mul(amount));
            }
            else{
                numTokens = numTokens.add(rate2.mul(r2));
                amount = amount.sub(r2);
                contributed2[addr] = cap2[addr];
            }
        }
        // Compute tokens for tier 1
        if(r1 > 0){
            if(amount <= r1){
                contributed1[addr] = contributed1[addr].add(amount);
                return numTokens.add(rate1.mul(amount));
            }
            else{
                numTokens = numTokens.add(rate1.mul(r1));
                amount = amount.sub(r1);
                contributed1[addr] = cap1[addr];
            }
        }
        // Compute tokens for tier 4 (overflow)
        contributed4[addr] = contributed4[addr].add(amount);
        return numTokens.add(rate4.mul(amount));
    }
// Solidity 0.4.18
/*
 * If the user was already registered, ensure that the new caps do not conflict previous contributions
 *
 * NOTE: cannot use SafeMath here, because it exceeds the local variable stack limit.
 * Should be ok since it is onlyOwner, and conditionals should guard the subtractions from underflow.
 */
function validateUpdatedRegistration(address addr, uint c1, uint c2, uint c3, uint c4)
        internal
        constant
        onlyOwner returns(bool)
    {
        return (contributed3[addr] <= c3) && (contributed2[addr] <= c2)
            && (contributed1[addr] <= c1) && (contributed4[addr] <= c4);
    }
// Solidity 0.4.18
/**
 * @dev Sets registration status of an address for participation.
 *
 * @param contributor Address that will be registered/deregistered.
 * @param c1 The maximum amount of wei that the user can contribute in tier 1.
 * @param c2 The maximum amount of wei that the user can contribute in tier 2.
 * @param c3 The maximum amount of wei that the user can contribute in tier 3.
 * @param c4 The maximum amount of wei that the user can contribute in tier 4.
 */
function registerUser(address contributor, uint c1, uint c2, uint c3, uint c4)
        public
        onlyOwner
    {
        require(contributor != address(0));
        // if the user was already registered ensure that the new caps do not contradict their current contributions
        if(hasPreviouslyRegistered(contributor)){
            require(validateUpdatedRegistration(contributor, c1, c2, c3, c4));
        }
        require(c1.add(c2).add(c3).add(c4) >= minContribution);
        registry[contributor] = true;
        cap1[contributor] = c1;
        cap2[contributor] = c2;
        cap3[contributor] = c3;
        cap4[contributor] = c4;
        RegistrationStatusChanged(contributor, true, c1, c2, c3, c4);
    }
// Solidity 0.4.18
/**
 * @dev Sets registration statuses of addresses for participation.
 * @param contributors Addresses that will be registered/deregistered.
 * @param caps1 The maximum amount of wei that each user can contribute to cap1, in the same order as the addresses.
 * @param caps2 The maximum amount of wei that each user can contribute to cap2, in the same order as the addresses.
 * @param caps3 The maximum amount of wei that each user can contribute to cap3, in the same order as the addresses.
 * @param caps4 The maximum amount of wei that each user can contribute to cap4, in the same order as the addresses.
 */
function registerUsers(address[] contributors,
                           uint[] caps1,
                           uint[] caps2,
                           uint[] caps3,
                           uint[] caps4)
        external
        onlyOwner
    {
        // check that all arrays have the same length
        require(contributors.length == caps1.length);
        require(contributors.length == caps2.length);
        require(contributors.length == caps3.length);
        require(contributors.length == caps4.length);
        for (uint i = 0; i < contributors.length; i++) {
            registerUser(contributors[i], caps1[i], caps2[i], caps3[i], caps4[i]);
        }
    }
// Solidity 0.4.18
/**
 *
 * The owner can allocate the specified amount of tokens from the
 * crowdsale allowance to the recipient (_to).
 *
 *
 *
 * NOTE: be extremely careful to get the amounts correct, which
 * are in units of wei and mini-QSP. Every digit counts.
 *
 * @param _to            the recipient of the tokens
 * @param amountWei     the amount contributed in wei
 * @param amountMiniQsp the amount of tokens transferred in mini-QSP
 */
function ownerAllocateTokens(address _to, uint amountWei, uint amountMiniQsp)
            onlyOwner nonReentrant
    {
        // don't allocate tokens for the admin
        // require(tokenReward.adminAddr() != _to);
        amountRaised = amountRaised.add(amountWei);
        require(amountRaised <= fundingCap);
        tokenBalanceOf[_to] = tokenBalanceOf[_to].add(amountMiniQsp);
        balanceOf[_to] = balanceOf[_to].add(amountWei);
        FundTransfer(_to, amountWei, true);
        updateFundingCap();
    }
// Solidity 0.4.18
/**
 * Checks if the funding cap has been reached. If it has, then
 * the CapReached event is triggered.
 */
function updateFundingCap() internal {
        assert (amountRaised <= fundingCap);
        if (amountRaised == fundingCap) {
            // Check if the funding cap has been reached
            fundingCapReached = true;
            saleClosed = true;
            CapReached(beneficiary, amountRaised);
        }
    }
// Solidity 0.8.7
/**
 * @notice Distributes rewards to token holders.
 * @dev It reverts if the total shares is 0.
 * It emits the `RewardsDistributed` event if the amount to distribute is greater than 0.
 * About undistributed rewards:
 *   In each distribution, there is a small amount which does not get distributed,
 *   which is `(amount * POINTS_MULTIPLIER) % totalShares()`.
 *   With a well-chosen `POINTS_MULTIPLIER`, the amount of funds that are not getting
 *   distributed in a distribution can be less than 1 (base unit).
 */
function _distributeRewards(uint256 _amount) internal {
    uint256 shares = getTotalShares();
    require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero");

    if (_amount > 0) {
      pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares);
      emit RewardsDistributed(msg.sender, _amount);
    }
  }
// Solidity 0.8.9
// Mint on behalf of bot contract
function mint(uint256 _optionId, address _toAddress) override public {
        // Must be sent from the owner proxy or owner.
        ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
        assert(
            owner() == _msgSender() || address(proxyRegistry.proxies(owner())) == _msgSender()      
        );
        require(canMint(_optionId), "Can't mint, out of supply or invalid factory token.");
        MetavotG1 metavot = MetavotG1(metavotAddress);
        metavot.mintRandomBot(_toAddress);
    }
// Solidity 0.8.11
/** TRANSFERS */
function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal override notBlackListed(from) {
        if (from != address(0)) {
            uint256 claimableBalanceSender = _claimableBalances[from];
            if (block.timestamp >= deployedTime + lockPeriod && claimableBalanceSender != 0) {
                _burnClaimable(from, claimableBalanceSender);
                _mint(from, claimableBalanceSender);
            }
        }

        super._beforeTokenTransfer(from, to, amount);
    }
// Solidity 0.4.18
// Multiple Transactions
function transferMulti(address[] _to, uint256[] _value) public returns (bool success) {
    require (_value.length==_to.length);

    for(uint256 i = 0; i < _to.length; i++) {
        require (balances[msg.sender] >= _value[i]);
        require (_to[i] != 0x0);

        super.transfer(_to[i], _value[i]);
    }
        return true;
  }
// Solidity 0.4.24
/***
 Rigister group aff for 1 eth
 */
function registerVIP()
    isHuman()
    public
    payable
    {
        require (msg.value >= registerVIPFee_, "Your eth is not enough to be group aff");
        // set up our tx event data and determine if player is new or not
        F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
        // fetch player id
        uint256 _pID = pIDxAddr_[msg.sender];

        //is vip already
        if(plyr_[_pID].vip) {
            revert();
        }

        //give myWallet the eth
        myWallet.transfer(msg.value);

        //save the info
        plyr_[_pID].vip = true;
        vipIDs_[vipPlayersCount_] = _pID;
        vipPlayersCount_++;
    }
// Solidity 0.4.24
/**
 is round in active?
 */
function isRoundActive()
    public
    view
    returns(bool)
    {
        // setup local rID
        uint256 _rID = rID_;

        // grab time
        uint256 _now = now;
        //过了休息时间，并且没有超过终止时间或超过了终止时间没有人购买，都算是激活
        return _now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0));
    }
// Solidity 0.4.24
/**
 random int
 */
function randInt(uint256 _start, uint256 _end, uint256 _nonce)
    private
    view
    returns(uint256)
    {
        uint256 _range = _end.sub(_start);
        uint256 seed = uint256(keccak256(abi.encodePacked(
                (block.timestamp).add
                (block.difficulty).add
                ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
                (block.gaslimit).add
                ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
                (block.number),
                    _nonce
            )));
        return (_start + seed - ((seed / _range) * _range));
    }
// Solidity 0.4.24
/**
 * @dev updates masks for round and player when keys are bought
 * @return dust left over
 */
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys, uint256 _eth)
    private
    returns(uint256)
    {
        uint256 _oldKeyValue = round_[_rID].mask;
        // calc profit per key & round mask based on this buy:  (dust goes to pot)
        uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
        round_[_rID].mask = _ppt.add(_oldKeyValue);

        //更新收益，计算可能的收益溢出
        updateGenVault(_pID, plyr_[_pID].lrnd, _keys, _eth);

        // calculate player earning from their own buy (only based on the keys
        // they just bought).  & update player earnings mask
//        uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
//        _pearn = ((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn);
//        plyrRnds_[_pID][_rID].mask = (_pearn).add(plyrRnds_[_pID][_rID].mask);

        plyrRnds_[_pID][_rID].mask = (_oldKeyValue.mul(_keys) / (1000000000000000000)).add(plyrRnds_[_pID][_rID].mask);

        // calculate & return dust
        return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
    }
// Solidity 0.7.4
/**
 * @notice send rewards
 * @param stakedToken Stake amount of the user
 * @param tokenAddress Reward token address
 * @param amount Amount to be transferred as reward
 */
function sendToken(address user, address stakedToken,address tokenAddress,uint256 amount) internal {
        // Checks
        if (tokenAddress != address(0)) {
            
            require(IERC20(tokenAddress).balanceOf(address(this)) >= amount, "SEND: Insufficient Balance in Contract");
            
            IERC20(tokenAddress).transfer(user, amount);
            
            emit Claim(
                user,
                stakedToken,
                tokenAddress,
                amount,
                block.timestamp
            );
          
        }
    }
// Solidity 0.7.4
/**
 * @notice Claim accumulated rewards
 * @param stakedAmount Staked amount of the user
 */
function claimRewards(address user,uint256 stakeTime, uint256 stakedAmount, address stakedToken, uint256 totalStake) internal {
        // Local variables
        uint256 interval;

        interval = stakeTime.add(stakeDuration);
        
        // Interval calculation
        if (interval > block.timestamp) {
            uint256 endOfProfit = block.timestamp;
            interval = endOfProfit.sub(stakeTime);
        } else {
            uint256 endOfProfit = stakeTime.add(stakeDuration);
            interval = endOfProfit.sub(stakeTime);
        }

        // Reward calculation
       if (interval >= DAYS)
            _rewardCalculation(user, stakedAmount, interval, stakedToken, totalStake);
    }
// Solidity 0.5.17
/**
 	 * Bypass to IMarketBehavior.authenticate.
 	 * Authenticates the new asset and proves that the Property author is the owner of the asset.
 	 */
function authenticate(
		address _prop,
		string memory _args1,
		string memory _args2,
		string memory _args3,
		string memory _args4,
		string memory _args5
	) public onlyPropertyAuthor(_prop) returns (bool) {
		uint256 len = bytes(_args1).length;
		require(len > 0, "id is required");

		return
			IMarketBehavior(behavior).authenticate(
				_prop,
				_args1,
				_args2,
				_args3,
				_args4,
				_args5,
				address(this)
			);
	}
// Solidity 0.5.17
/**
 	 * A function that will be called back when the asset is successfully authenticated.
 	 * There are cases where oracle is required for the authentication process, so the function is used callback style.
 	 */
function authenticatedCallback(address _property, bytes32 _idHash)
		external
		returns (address)
	{
		/**
		 * Validates the sender is the saved IMarketBehavior address.
		 */
		addressValidator().validateAddress(msg.sender, behavior);
		require(enabled, "market is not enabled");

		/**
		 * Validates the assets are not double authenticated.
		 */
		require(idMap[_idHash] == false, "id is duplicated");
		idMap[_idHash] = true;

		/**
		 * Gets the Property author address.
		 */
		address sender = IProperty(_property).author();

		/**
		 * Publishes a new Metrics contract and associate the Property with the asset.
		 */
		IMetricsFactory metricsFactory = IMetricsFactory(
			config().metricsFactory()
		);
		address metrics = metricsFactory.create(_property);
		idHashMetricsMap[metrics] = _idHash;

		/**
		 * Burn as a authentication fee.
		 */
		uint256 authenticationFee = getAuthenticationFee(_property);
		require(
			Dev(config().token()).fee(sender, authenticationFee),
			"dev fee failed"
		);

		/**
		 * Adds the number of authenticated assets in this Market.
		 */
		issuedMetrics = issuedMetrics.add(1);
		return metrics;
	}
// Solidity 0.5.17
/**
 	 * Release the authenticated asset.
 	 */
function deauthenticate(address _metrics)
		external
		onlyLinkedPropertyAuthor(_metrics)
	{
		/**
		 * Validates the passed Metrics address is authenticated in this Market.
		 */
		bytes32 idHash = idHashMetricsMap[_metrics];
		require(idMap[idHash], "not authenticated");

		/**
		 * Removes the authentication status from local variables.
		 */
		idMap[idHash] = false;
		idHashMetricsMap[_metrics] = bytes32(0);

		/**
		 * Removes the passed Metrics contract from the Metrics address set.
		 */
		IMetricsFactory metricsFactory = IMetricsFactory(
			config().metricsFactory()
		);
		metricsFactory.destroy(_metrics);

		/**
		 * Subtracts the number of authenticated assets in this Market.
		 */
		issuedMetrics = issuedMetrics.sub(1);
	}
// Solidity 0.8.9
/**
 * @dev Gives a random token to the provided address
 */
function devMintTokensToAddresses(uint8 _tokenBorderId, address[] memory _addresses) external onlyOwner contractIsNotFrozen {
        require(_addresses.length > 0, "At least one token should be minted");
        require(getAvailableTokens(_tokenBorderId) >= _addresses.length, "Not enough tokens available");

        uint16[10] memory tmpAvailableTokens = availableTokens;

        for (uint256 i; i < _addresses.length; i++) {
            uint8 tokenTypeIndex = _getRandomNumber(availableTokensIds[_tokenBorderId].length, i);

            _mint(_addresses[i], availableTokensIds[_tokenBorderId][tokenTypeIndex], 1, "");

            tmpAvailableTokens[availableTokensIds[_tokenBorderId][tokenTypeIndex]]--;

            if (tmpAvailableTokens[availableTokensIds[_tokenBorderId][tokenTypeIndex]] == 0) {
                availableTokensIds[_tokenBorderId][tokenTypeIndex] = availableTokensIds[_tokenBorderId][availableTokensIds[_tokenBorderId].length - 1];
                availableTokensIds[_tokenBorderId].pop();        
            }
        }

        availableTokens = tmpAvailableTokens;
    }
// Solidity 0.8.9
/**
 * @dev Set the total amount of tokens
 */
function addSupply(uint8 _tokenType, uint16 _supply) external onlyOwner contractIsNotFrozen {
        require(_tokenType < 10, "Token type should be between 0 and 9");
        require(_supply > 0, "Supply should be greater than 0");

        availableTokens[_tokenType] += _supply;

        uint8 tokenBorderType = _tokenType < 5 ? RED_BORDER_TOKEN_ID : WHITE_BORDER_TOKEN_ID;

        bool isTokenTypeAvailable = false;

        for (uint256 i; i < availableTokensIds[tokenBorderType].length; i++) {
            if (availableTokensIds[tokenBorderType][i] == _tokenType) {
                isTokenTypeAvailable = true;
                break;
            }
        }

        if (!isTokenTypeAvailable) {
            availableTokensIds[tokenBorderType].push(_tokenType);
        }
    }
// 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.
 @param _auxData Unused parameter, can be used for everything, for example, writing IDs of apps from which the deposit was made.
 @notice Emits {Deposit} event.
 */
function deposit(uint8 destinationChainID, bytes32 resourceID, bytes calldata data, bytes calldata _auxData) external payable whenNotPaused {
        require(msg.value == _fees[destinationChainID], "Incorrect fee supplied");

        address handler = _resourceIDToHandlerAddress[resourceID];
        require(handler != address(0), "resourceID not mapped to handler");

        uint64 depositNonce = ++_depositCounts[destinationChainID];

        IDepositExecute depositHandler = IDepositExecute(handler);
        depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);

        emit Deposit(destinationChainID, resourceID, depositNonce);
    }
// Solidity 0.6.4
/**
 @notice When called, {msg.sender} will be marked as voting in favor of proposal.
 @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 data data provided when deposit was made.
 @notice Proposal must not have already been passed or executed.
 @notice {msg.sender} must not have already voted on proposal.
 @notice Emits {ProposalEvent} event with status indicating the proposal status.
 @notice Emits {ProposalVote} event.
 */
function voteProposal(uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes calldata data) external onlyRelayers whenNotPaused {
        address handler = _resourceIDToHandlerAddress[resourceID];
        bytes32 dataHash = keccak256(abi.encodePacked(handler, data));

        uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
        Proposal storage proposal = _proposals[nonceAndID][dataHash];

        require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
        require(uint(proposal._status) <= 1, "proposal already executed");
        require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");

        if (uint(proposal._status) == 0) {
            ++_totalProposals;
            _proposals[nonceAndID][dataHash] = Proposal({
                _resourceID : resourceID,
                _dataHash : dataHash,
                _yesVotes : new address[](1),
                _noVotes : new address[](0),
                _status : ProposalStatus.Active,
                _proposedBlock : block.number
                });

            proposal._yesVotes[0] = msg.sender;
            emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
        } else {
            require(dataHash == proposal._dataHash, "datahash mismatch");
            proposal._yesVotes.push(msg.sender);
        }
        
        _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
        emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);

        // if _relayerThreshold has been exceeded
        if (proposal._yesVotes.length >= _relayerThreshold) {
            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.6.5
/// @notice enable Admin to withdraw remaining assets from EstateSaleWithFee contract
/// @param to intended recipient of the asset tokens
/// @param assetIds the assetIds to be transferred
/// @param values the quantities of the assetIds to be transferred
function withdrawAssets(
        address to,
        uint256[] calldata assetIds,
        uint256[] calldata values
    ) external {
        require(msg.sender == _admin, "NOT_AUTHORIZED");
        // require(block.timestamp > _expiryTime, "SALE_NOT_OVER"); // removed to recover in case of misconfigured sales
        _asset.safeBatchTransferFrom(address(this), to, assetIds, values, "");
    }
// Solidity 0.4.19
/// For creating City
function _createCity(string _name, string _country, address _owner, uint256 _price) private {
    City memory _city = City({
      name: _name,
      country: _country
    });
    uint256 newCityId = cities.push(_city) - 1;

    // It's probably never going to happen, 4 billion tokens are A LOT, but
    // let's just be 100% sure we never let this happen.
    require(newCityId == uint256(uint32(newCityId)));

    CityCreated(newCityId, _name, _country, _owner);

    cityIndexToPrice[newCityId] = _price;

    // This will assign ownership, and also emit the Transfer event as
    // per ERC721 draft
    _transfer(address(0), _owner, newCityId);
  }