lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.11
// Internal Order Placement.
//
// Charge the client for the cost of placing an order in the given direction.
//
// Return true if successful, false otherwise.
//
function debitFunds(
      address client, Direction direction, uint sizeBase, uint sizeCntr
    ) internal returns (bool success) {
    if (direction == Direction.Buy) {
      uint availableCntr = balanceCntrForClient[client];
      if (availableCntr < sizeCntr) {
        return false;
      }
      balanceCntrForClient[client] = availableCntr - sizeCntr;
      return true;
    } else if (direction == Direction.Sell) {
      uint availableBase = balanceBaseForClient[client];
      if (availableBase < sizeBase) {
        return false;
      }
      balanceBaseForClient[client] = availableBase - sizeBase;
      return true;
    } else {
      return false;
    }
  }
// Solidity 0.4.11
// Internal Book View.
//
// See walkBook - adds up open depth at a price starting from an
// order which is assumed to be open. Careful - unlimited gas use.
//
function sumDepth(uint128 orderId) internal constant returns (uint depth, uint orderCount) {
    while (true) {
      Order storage order = orderForOrderId[orderId];
      depth += order.sizeBase - order.executedBase;
      orderCount++;
      orderId = orderChainNodeForOpenOrderId[orderId].nextOrderId;
      if (orderId == 0) {
        return (depth, orderCount);
      }
    }
  }
// Solidity 0.6.12
/**
 * @dev Withdraws reward for holder. Returns reward.
 */
function withdrawReward() public returns (uint256) {
        updateTotalReward();
        uint256 value = calcReward(msg.sender) + owed[msg.sender];
        rewardAtTimeOfWithdraw[msg.sender] = totalReward;
        owed[msg.sender] = 0;

        require(value > 0, "DevFund: withdrawReward nothing to transfer");

        rewardToken.transfer(msg.sender, value);

        prevBalance = rewardToken.balanceOf(address(this));

        return value;
    }
// Solidity 0.6.12
/**
 * @dev View remaining reward for an address.
 * @param forAddress holder's address.
 */
function rewardFor(address forAddress) public view returns (uint256) {
        uint256 _currentBalance = rewardToken.balanceOf(address(this));
        uint256 _totalReward = totalReward +
            (_currentBalance > prevBalance ? _currentBalance - prevBalance : 0);
        return
            owed[forAddress] +
            (holderToken.balanceOf(forAddress) *
                (_totalReward - rewardAtTimeOfWithdraw[forAddress])) /
            holderToken.totalSupply();
    }
// Solidity 0.4.24
// /**
//  * Transfer tokens
//  *
//  * Send `_value` tokens to `_to` from your account
//  *
//  * @param _to The address of the recipient
//  * @param _value the amount to send
//  */
// function transfer(address _to, uint256 _value) public {
//     _transfer(msg.sender, _to, _value);
// }
function transfer (address _to, uint256 _amount) public returns (bool success) {
        if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {

            balances[msg.sender] -= _amount;
            balances[_to] += _amount;
            emit Transfer(msg.sender, _to, _amount);
            return true;
        } else {
            return false;
        }
    }
// Solidity 0.4.24
/**
 @notice Converts country index list into 3 uints
 
 Expects a list of country indexes such that the 2 digit country code is converted to an 
 index. Countries are expected to be indexed so a "AA" country code is mapped to index 0 and 
 "ZZ" country is mapped to index 675.
 @param countries List of country indexes
 @return {
 "countries1" : "First third of the byte array converted in a 256 bytes uint",
 "countries2" : "Second third of the byte array converted in a 256 bytes uint",
 "countries3" : "Third third of the byte array converted in a 256 bytes uint"
 }
 */
function convertCountryIndexToBytes(uint[] countries) public pure
        returns (uint countries1,uint countries2,uint countries3){
        countries1 = 0;
        countries2 = 0;
        countries3 = 0;
        for(uint i = 0; i < countries.length; i++){
            uint index = countries[i];

            if(index<256){
                countries1 = countries1 | uint(1) << index;
            } else if (index<512) {
                countries2 = countries2 | uint(1) << (index - 256);
            } else {
                countries3 = countries3 | uint(1) << (index - 512);
            }
        }

        return (countries1,countries2,countries3);
    }
// Solidity 0.4.24
/**
 @notice Add or update a campaign information
 
 Based on a campaign Id (bidId), a campaign can be created (if non existent) or updated.
 This function can only be called by the set of allowed addresses registered earlier.
 An event will be emited during this function's execution, a CampaignCreated event if the 
 campaign does not exist yet or a CampaignUpdated if the campaign id is already registered.
 
 @param bidId Id of the campaign
 @param price Value to pay for each proof-of-attention
 @param budget Total value avaliable to be spent on the campaign
 @param startDate Start date of the campaign (in miliseconds)
 @param endDate End date of the campaign (in miliseconds)
 @param valid Boolean informing if the campaign is valid
 @param owner Address of the campaing's owner
 */
function _setCampaign (
        bytes32 bidId,
        uint price,
        uint budget,
        uint startDate,
        uint endDate,
        bool valid,
        address owner
    )
    public
    onlyIfWhitelisted("setCampaign",msg.sender) {

        CampaignLibrary.Campaign storage campaign = campaigns[bidId];
        campaign.setBidId(bidId);
        campaign.setPrice(price);
        campaign.setBudget(budget);
        campaign.setStartDate(startDate);
        campaign.setEndDate(endDate);
        campaign.setValidity(valid);

        bool newCampaign = (campaigns[bidId].getOwner() == 0x0);

        campaign.setOwner(owner);



        if(newCampaign){
            emitCampaignCreated(campaign);
            setLastBidId(bidId);
        } else {
            emitCampaignUpdated(campaign);
        }
    }
// Solidity 0.4.24
/**
 @notice Get a Campaign information
 
 Based on a camapaign Id (bidId), returns all stored information for that campaign.
 @param _campaignId Id of the campaign
 @return {
 "_bidId" : "Id of the campaign",
 "_price" : "Value to pay for each proof-of-attention",
 "_budget" : "Total value avaliable to be spent on the campaign",
 "_startDate" : "Start date of the campaign (in miliseconds)",
 "_endDate" : "End date of the campaign (in miliseconds)"
 "_valid" : "Boolean informing if the campaign is valid",
 "_campOwner" : "Address of the campaing's owner",
 }
 */
function getCampaign(bytes32 _campaignId)
        public
        view
        returns (
            bytes32 _bidId,
            uint _price,
            uint _budget,
            uint _startDate,
            uint _endDate,
            bool _valid,
            address _campOwner
        ) {

        CampaignLibrary.Campaign storage campaign = _getCampaign(_campaignId);

        return (
            campaign.getBidId(),
            campaign.getPrice(),
            campaign.getBudget(),
            campaign.getStartDate(),
            campaign.getEndDate(),
            campaign.getValidity(),
            campaign.getOwner()
        );
    }
// Solidity 0.4.24
/**
 @notice Upgrade finance contract used by this contract
 
 This function is part of the upgrade mechanism avaliable to the advertisement contracts.
 Using this function it is possible to update to a new Advertisement Finance contract without
 the need to cancel avaliable campaigns.
 Upgrade finance function can only be called by the Advertisement contract owner.
 @param addrAdverFinance Address of the new Advertisement Finance contract
 */
function upgradeFinance (address addrAdverFinance) public onlyOwner("upgradeFinance") {
        BaseFinance newAdvFinance = BaseFinance(addrAdverFinance);

        address[] memory devList = advertisementFinance.getUserList();
        
        for(uint i = 0; i < devList.length; i++){
            uint balance = advertisementFinance.getUserBalance(devList[i]);
            newAdvFinance.increaseBalance(devList[i],balance);
        }
        
        uint256 initBalance = appc.balanceOf(address(advertisementFinance));
        advertisementFinance.transferAllFunds(address(newAdvFinance));
        uint256 oldBalance = appc.balanceOf(address(advertisementFinance));
        uint256 newBalance = appc.balanceOf(address(newAdvFinance));
        
        require(initBalance == newBalance);
        require(oldBalance == 0);
        advertisementFinance = newAdvFinance;
    }
// Solidity 0.4.24
/**
 @notice Creates a campaign 
 
 Method to create a campaign of user aquisition for a certain application.
 This method will emit a Campaign Information event with every information 
 provided in the arguments of this method.
 @param packageName Package name of the appication subject to the user aquisition campaign
 @param countries Encoded list of 3 integers intended to include every 
 county where this campaign will be avaliable.
 For more detain on this encoding refer to wiki documentation.
 @param vercodes List of version codes to which the user aquisition campaign is applied.
 @param price Value (in wei) the campaign owner pays for each proof-of-attention.
 @param budget Total budget (in wei) the campaign owner will deposit 
 to pay for the proof-of-attention.
 @param startDate Date (in miliseconds) on which the campaign will start to be 
 avaliable to users.
 @param endDate Date (in miliseconds) on which the campaign will no longer be avaliable to users.
 */
function _generateCampaign (
        string packageName,
        uint[3] countries,
        uint[] vercodes,
        uint price,
        uint budget,
        uint startDate,
        uint endDate)
        internal returns (CampaignLibrary.Campaign memory) {

        require(budget >= price);
        require(endDate >= startDate);


        //Transfers the budget to contract address
        if(appc.allowance(msg.sender, address(this)) >= budget){
            appc.transferFrom(msg.sender, address(advertisementFinance), budget);

            advertisementFinance.increaseBalance(msg.sender,budget);

            uint newBidId = bytesToUint(lastBidId);
            lastBidId = uintToBytes(++newBidId);
            

            CampaignLibrary.Campaign memory newCampaign;
            newCampaign.price = price;
            newCampaign.startDate = startDate;
            newCampaign.endDate = endDate;
            newCampaign.budget = budget;
            newCampaign.owner = msg.sender;
            newCampaign.valid = true;
            newCampaign.bidId = lastBidId;
        } else {
            emit Error("createCampaign","Not enough allowance");
        }
        
        return newCampaign;
    }
// Solidity 0.4.24
/**
 @notice Cancel a campaign and give the remaining budget to the campaign owner
 
 When a campaing owner wants to cancel a campaign, the campaign owner needs
 to call this function. This function can only be called either by the campaign owner or by
 the Advertisement contract owner. This function results in campaign cancelation and
 retreival of the remaining budget to the respective campaign owner.
 @param bidId Campaign id to which the cancelation referes to
 */
function cancelCampaign (bytes32 bidId) public {
        address campaignOwner = getOwnerOfCampaign(bidId);

		// Only contract owner or campaign owner can cancel a campaign
        require(owner == msg.sender || campaignOwner == msg.sender);
        uint budget = getBudgetOfCampaign(bidId);

        advertisementFinance.withdraw(campaignOwner, budget);

        advertisementStorage.setCampaignBudgetById(bidId, 0);
        advertisementStorage.setCampaignValidById(bidId, false);
    }
// Solidity 0.4.24
/**
 @notice Check if a certain campaign is still valid
 
 Returns a boolean representing the validity of the campaign
 Has value of True if the campaign is still valid else has value of False
 @param bidId Campaign id to which the query refers
 @return { "valid" : "validity of the campaign" }
 */
function isCampaignValid(bytes32 bidId) public view returns(bool valid) {
        uint startDate = advertisementStorage.getCampaignStartDateById(bidId);
        uint endDate = advertisementStorage.getCampaignEndDateById(bidId);
        bool validity = advertisementStorage.getCampaignValidById(bidId);

        uint nowInMilliseconds = now * 1000;
        return validity && startDate < nowInMilliseconds && endDate > nowInMilliseconds;
    }
// Solidity 0.4.24
/**
 @notice splitSignature
 
 Based on a signature Sig (bytes32), returns the r, s, v
 @param sig Signature
 @return {
 "uint8" : "recover Id",
 "bytes32" : "Output of the ECDSA signature",
 "bytes32" : "Output of the ECDSA signature",
 }
 */
function splitSignature(bytes sig)
        internal
        pure
        returns (uint8, bytes32, bytes32)
        {
        require(sig.length == 65);

        bytes32 r;
        bytes32 s;
        uint8 v;

        assembly {
            // first 32 bytes, after the length prefix
            r := mload(add(sig, 32))
            // second 32 bytes
            s := mload(add(sig, 64))
            // final byte (first byte of the next 32 bytes)
            v := byte(0, mload(add(sig, 96)))
        }

        return (v, r, s);
    }
// Solidity 0.4.24
/**
 @notice Sets the Advertisement contract address to allow calls from Advertisement contract
 
 This function is used for upgrading the Advertisement contract without need to redeploy 
 Advertisement Finance and Advertisement Storage contracts. The function can only be called 
 by this contract's owner. During the update of the Advertisement contract address, the 
 contract for Advertisement Storage used by the new Advertisement contract is checked. 
 This function reverts if the new Advertisement contract does not use the same Advertisement 
 Storage contract earlier registered in this Advertisement Finance contract.
 @param _addr Address of the newly allowed contract 
 */
function setAllowedAddress (address _addr) public onlyOwner("setAllowedAddress") {
        // Verify if the new Ads contract is using the same storage as before 
        if (allowedAddress != 0x0){
            StorageUser storageUser = StorageUser(_addr);
            address storageContract = storageUser.getStorageAddress();
            require (storageContract == advStorageContract);
        }
        
        //Update contract
        super.setAllowedAddress(_addr);
    }
// Solidity 0.4.24
/**
 @notice Creates an extebded campaign
 */
function createCampaign (
        string packageName,
        uint[3] countries,
        uint[] vercodes,
        uint price,
        uint budget,
        uint startDate,
        uint endDate,
        string endPoint)
        external
        {

        CampaignLibrary.Campaign memory newCampaign = _generateCampaign(packageName, countries, vercodes, price, budget, startDate, endDate);

        if(newCampaign.owner == 0x0){
            // campaign was not generated correctly (revert)
            return;
        }

        _getBidIdList().push(newCampaign.bidId);

        ExtendedAdvertisementStorage(address(_getStorage())).setCampaign(
            newCampaign.bidId,
            newCampaign.price,
            newCampaign.budget,
            newCampaign.startDate,
            newCampaign.endDate,
            newCampaign.valid,
            newCampaign.owner,
            endPoint);

        emit CampaignInformation(
            newCampaign.bidId,
            newCampaign.owner,
            "", // ipValidator field
            packageName,
            countries,
            vercodes,
            endPoint);
    }
// Solidity 0.4.24
/**
 @notice Function to submit in bulk PoAs
 @param bidId Campaign id for which the Proof of attention root hash refferes to
 @param rootHash Root hash of all submitted proof of attention to a given campaign
 @param signedRootHash Root hash signed by the signing service of the campaign
 @param newHashes Number of new proof of attention hashes since last submission
 */
function bulkRegisterPoA(bytes32 bidId, bytes32 rootHash, bytes signedRootHash, uint256 newHashes)
        public
        onlyIfWhitelisted("createCampaign",msg.sender)
        {

        /* address addressSig = recoverSigner(rootHash, signedRootHash); */

        /* if (msg.sender != addressSig) {
            emit Error("bulkRegisterPoA","Invalid signature");
            return;
        } */

        uint price = _getStorage().getCampaignPriceById(bidId);
        uint budget = _getStorage().getCampaignBudgetById(bidId);
        address owner = _getStorage().getCampaignOwnerById(bidId);
        uint maxConversions = division(budget,price);
        uint effectiveConversions;
        uint totalPay;
        uint newBudget;

        if (maxConversions >= newHashes){
            effectiveConversions = newHashes;
        } else {
            effectiveConversions = maxConversions;
        }

        totalPay = price*effectiveConversions;
        newBudget = budget - totalPay;

        _getFinance().pay(owner,msg.sender,totalPay);
        _getStorage().setCampaignBudgetById(bidId,newBudget);

        if(newBudget < price){
            _getStorage().setCampaignValidById(bidId,false);
        }

        emit BulkPoARegistered(bidId,rootHash,signedRootHash,newHashes,effectiveConversions);
    }
// Solidity 0.8.7
/** ========== main functions ========== */
function mint() external payable nonReentrant returns (uint256)  {

        require(!userMinted[_msgSender()], "mint: you have claimed one token");
        require(usertokenCounters.current() < MAX_AMOUNT_USER, "mint: all tokens have been minted");
        // users must pay for the NFT
        require(msg.value >= META_PRICE, "mint: not enough to pay");

        usertokenCounters.increment();
        uint256 mintingTokenId = usertokenCounters.current();

        // data update
        userMinted[_msgSender()] = true;

        // mint
        _safeMint(_msgSender(), mintingTokenId);

        emit claimed(_msgSender(), mintingTokenId);

        return mintingTokenId;
    }
// Solidity 0.8.7
/** ========== internal mutative functions ========= */
function _claim(address receiver) internal {     
        require(receiver != address(0), "claim: invalid address");   
        
        ownertokenCounters.increment();
        uint256 mintId = ownertokenCounters.current() + MAX_AMOUNT_USER;
        require(mintId > MAX_AMOUNT_USER && mintId <= MAX_AMOUNT, "ownerClaim: all tokens have been claimed");

        // mint
        _safeMint(receiver, mintId);

        emit claimed(receiver, mintId);
    }
// Solidity 0.8.0
/// @dev Adds Distribution. This function doesn't limit max gas consumption,
/// so adding too many investors can cause it to reach the out-of-gas error.
/// @param _beneficiary The address of distribution.
/// @param _tokensAllotment The amounts of the tokens that belong to each investor.
function _addDistribution(
        address _beneficiary,
        DistributionType _distributionType,
        uint256 _tokensAllotment
    ) internal {
        require(_beneficiary != address(0), "Invalid address");
        require(
            _tokensAllotment > 0,
            "the investor allocation must be more than 0"
        );
        Distribution storage distribution = distributionInfo[_distributionType];

        require(distribution.tokensAllotment == 0, "investor already added");

        distribution.beneficiary = _beneficiary;
        distribution.tokensAllotment = _tokensAllotment;
        distribution.distributionType = _distributionType;

        emit DistributionAdded(_beneficiary, _msgSender(), _tokensAllotment);
    }
// Solidity 0.6.12
// Check if current block's base fee is under max allowed base fee
function isCurrentBaseFeeAcceptable() public view returns (bool) {
        uint256 baseFee;
        try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) {
            baseFee = currentBaseFee;
        } catch {
            // Useful for testing until ganache supports london fork
            // Hard-code current base fee to 1000 gwei
            // This should also help keepers that run in a fork without
            // baseFee() to avoid reverting and potentially abandoning the job
            baseFee = 1000 * 1e9;
        }

        return baseFee <= maxAcceptableBaseFee;
    }
// Solidity 0.5.17
/**
 * @notice Applies accrued interest to total borrows and reserves
 * @dev This calculates interest accrued from the last checkpointed block
 *   up to the current block and writes new checkpoint to storage.
 */
function accrueInterest() public returns (uint) {
        /* Remember the initial block number */
        uint currentBlockNumber = getBlockNumber();

        /* Short-circuit accumulating 0 interest */
        if (accrualBlockNumber == currentBlockNumber) {
            return uint(Error.NO_ERROR);
        }

        /* Read the previous values out of storage */
        uint cashPrior = getCashPrior();

        /* Calculate the current borrow interest rate */
        uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, totalBorrows, add_(totalReserves, add_(totalAdminFees, totalFuseFees)));
        require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");

        /* Calculate the number of blocks elapsed since the last accrual */
        (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumber);
        require(mathErr == MathError.NO_ERROR, "could not calculate block delta");

        return finishInterestAccrual(currentBlockNumber, cashPrior, borrowRateMantissa, blockDelta);
    }
// Solidity 0.5.17
/**
 * @notice Reduces reserves by transferring to admin
 * @dev Requires fresh interest accrual
 * @param reduceAmount Amount of reduction to reserves
 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
 */
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
        // totalReserves - reduceAmount
        uint totalReservesNew;

        // Check caller is admin
        if (!hasAdminRights()) {
            return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
        }

        // We fail gracefully unless market's block number equals current block number
        if (accrualBlockNumber != getBlockNumber()) {
            return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
        }

        // Fail gracefully if protocol has insufficient underlying cash
        if (getCashPrior() < reduceAmount) {
            return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
        }

        // Check reduceAmount ≤ reserves[n] (totalReserves)
        if (reduceAmount > totalReserves) {
            return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
        }

        /////////////////////////
        // EFFECTS & INTERACTIONS
        // (No safe failures beyond this point)

        // We checked reduceAmount <= totalReserves above, so this should never revert.
        totalReservesNew = sub_(totalReserves, reduceAmount);

        // Store reserves[n+1] = reserves[n] - reduceAmount
        totalReserves = totalReservesNew;

        // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
        doTransferOut(msg.sender, reduceAmount);

        emit ReservesReduced(msg.sender, reduceAmount, totalReservesNew);

        return uint(Error.NO_ERROR);
    }