lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/* Calculate realtime User Staking Score. */
function getPendingReward(address _holder) public view returns (uint) {
        if (!holders.contains(_holder)) return 0;
        if (depositedTokens[_holder] == 0) return 0;

        uint timeDiff = now.sub(lastClaimedTime[_holder]);
        uint stakedAmount = depositedTokens[_holder];
        
        uint pendingDivs = stakedAmount
                            .mul(rewardRate)
                            .mul(timeDiff)
                            .div(rewardInterval)
                            .div(1e4);
            
        return pendingDivs;
    }
// Solidity 0.6.12
/* Record Staking with Offer check. */
function stake(uint amountToStake) public {
        require(amountToStake > 0, "Cannot deposit 0 Tokens");
        require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
        emit TokenStaked(msg.sender, amountToStake, now);
        
        updateAccount(msg.sender);
        updateLastScoreTime(msg.sender);
        totalStakedToken = totalStakedToken.add(amountToStake);
        
        if(stakingOffer > now){
            uint offerRaise = amountToStake.mul(stakingOfferRaise).div(1e4);          
            totalOfferRaise = totalOfferRaise.add(offerRaise);
            totalOfferUser[msg.sender] = offerRaise ;
            emit OfferStaked(totalStakedToken, now);

            amountToStake = amountToStake.add(offerRaise);
        }

            emit AllTokenStaked(totalStakedToken, now);


        depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake);

        if (!holders.contains(msg.sender)) {
            holders.add(msg.sender);
            stakingTime[msg.sender] = now;
        }
    }
// Solidity 0.6.12
/* Record UnStaking. */
function unstake(uint amountToWithdraw) public {

        require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");        
         
        updateAccount(msg.sender);
        
        uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
        uint amountAfterFee = amountToWithdraw.sub(fee);
        
        require(Token(tokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
        emit TokenUnstaked(msg.sender, amountAfterFee,now);
     
        require(Token(tokenAddress).transfer(burnAddress, fee), "Could not burn fee.");
        emit TokenBurned(fee,now);
       
        totalUnstakedToken = totalUnstakedToken.add(amountAfterFee);
        totalFeeCollected = totalFeeCollected.add(fee);
        emit AllTokenUnStaked(totalUnstakedToken, now);
        
        uint timeDiff = 0 ;
        
        if(lastScoreTime[msg.sender] > 0){
            timeDiff = now.sub(lastScoreTime[msg.sender]).div(2);            
        }
      
        uint score = amountAfterFee
                            .mul(scoreRate)
                            .mul(timeDiff)
                            .div(scoreInterval)
                            .div(1e4);
            
        
         
        uint eth = score.div(scoreEth);     
        totalEthClaimed = totalEthClaimed.add(eth);

        msg.sender.transfer(eth);
        emit EthClaimed(msg.sender ,eth,now);

        lastScoreTime[msg.sender] = now;

        depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
        
        if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
            holders.remove(msg.sender);
        }
    }
// Solidity 0.6.12
/* Claim ETH Equivalent to Score. */
function claimScoreEth() public {
        uint timeDiff = 0 ;
        
        if(lastScoreTime[msg.sender] > 0){
            timeDiff = now.sub(lastScoreTime[msg.sender]).div(2);            
        }

        uint stakedAmount = depositedTokens[msg.sender];       
       
        uint score = stakedAmount
                            .mul(scoreRate)
                            .mul(timeDiff)
                            .div(scoreInterval)
                            .div(1e4);                    
         
        uint eth = score.div(scoreEth);     
        totalEthClaimed = totalEthClaimed.add(eth);
        msg.sender.transfer(eth);
        emit EthClaimed(msg.sender , eth,now);
 
        
        lastScoreTime[msg.sender] = now;
    
    }
// Solidity 0.8.12
/// @notice Get token's URI. In case of delayed reveal we give user the json of the placeholer metadata.
/// @param tokenId token ID
function tokenURI(uint tokenId) public view override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        
        if(!canReveal) {
            return _hiddenURI;
        }
        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : "";
    }
// Solidity 0.6.12
// Deposit LP tokens to MasterChef for VEMP allocation.
function deposit(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        if (user.amount > 0) {
            uint256 pending = user.amount.mul(pool.accVEMPPerShare).div(1e12).sub(user.rewardDebt);
            safeVEMPTransfer(msg.sender, pending);
            
            uint256 SANDReward = user.amount.mul(pool.accSANDPerShare).div(1e12).sub(user.rewardSANDDebt);
            pool.lpToken.safeTransfer(msg.sender, SANDReward);
            pool.lastSANDRewardBalance = pool.lpToken.balanceOf(address(this)).sub(totalSANDStaked.sub(totalSANDUsedForPurchase));
        }
        pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
        totalSANDStaked = totalSANDStaked.add(_amount);
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accVEMPPerShare).div(1e12);
        user.rewardSANDDebt = user.amount.mul(pool.accSANDPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.6.12
// Safe SAND transfer function to admin.
function accessSANDTokens(uint256 _pid, address _to, uint256 _amount) public {
        require(msg.sender == adminaddr, "sender must be admin address");
        require(totalSANDStaked.sub(totalSANDUsedForPurchase) >= _amount, "Amount must be less than staked SAND amount");
        PoolInfo storage pool = poolInfo[_pid];
        uint256 SANDBal = pool.lpToken.balanceOf(address(this));
        if (_amount > SANDBal) {
            pool.lpToken.transfer(_to, SANDBal);
            totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(SANDBal);
        } else {
            pool.lpToken.transfer(_to, _amount);
            totalSANDUsedForPurchase = totalSANDUsedForPurchase.add(_amount);
        }
    }
// Solidity 0.6.12
/**
 * Destroy tokens from other account
 *
 * Remove `_value` tokens from the system irreversibly on behalf of `_from`.
 *
 * @param _from the address of the sender
 * @param _value the amount of token minimal units (10**(-18)) to burn
 */
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool) {
        require(balanceOf[_from] >= _value, "address balance is smaller, than amount to burn");
        balanceOf[_from] -= _value;                         // Subtract from the targeted balance
        totalSupply -= _value;                              // Update totalSupply
        emit Burn(_from, _value);
		assert(totalSupply >= 0);
        return true;
    }
// Solidity 0.6.12
/**
 * Create new tokens to account
 	 *
 	 * Create _mintAmount of new tokens to account _target
 	 *
 	 * @param _mintAmount the amount of token minimal units (10**(-18)) to mint
 	 * @param _target the address to own new mint tokens
 *
 * Internal function, can be called from the contract and it's children contracts only
 */
function _mintToken(address _target, uint256 _mintAmount) internal {
		require(_target != address(0), "mint attempt to zero address"); // Prevent mint to 0x0 address.
		require(totalSupply + _mintAmount > totalSupply);
        balanceOf[_target] += _mintAmount;
        totalSupply += _mintAmount;
        emit Mint(_target, _mintAmount);
    }
// Solidity 0.8.9
/**
 * @dev Transfer NFTs if there is any in this contract to address `to`.
 */
function transfer(address to) external onlyOwner {
        require(isEnded, "Not ended");
        uint256 tokenId = _tokenOf(address(this));
        require(tokenId != 0, "No token to be transferred in this contract");
        require(specialWallets[to], "Must transfer to a special wallet");

        _transfer(address(this), to, tokenId);
    }
// Solidity 0.8.9
/**
 * @dev Returns all `tokenId`s for a given `class`.
 */
function getTokenIdsForClass(uint256 class) external view returns (uint256[] memory) {
        uint256 index = _getClassIndex(class);
        uint256[] memory tokenIds = new uint256[](index+1);
        if (index == 0) {
            tokenIds[0] = _tokenOf(_getWalletByClass(class));
            return tokenIds;
        } else {
            for (uint256 i = 0; i < index+1; i++) {
                tokenIds[i] = _tokenOf(_getWalletByIndex(class, i));
            }
            return tokenIds;
        }
    }
// Solidity 0.8.9
/**
 * @dev Execute the logic of making a contribution by `account`.
 */
function _contribute(address account) private {
        uint256 tokenId = _tokenOf(account);
        uint256 weight = _massOf(tokenId);
        (address targetWallet, uint256 class) = _getTargetWallet(tokenId);

        _transfer(account, targetWallet, tokenId);
        _mint(account, weight);
        _updateInfo(account, class, weight);

        emit Contribute(account, targetWallet, tokenId, class, weight);
    }
// Solidity 0.8.9
/**
 * @dev Returns the target wallet address by `class` and `tokenId`.
 */
function _getTargetWallet(uint256 tokenId) private returns (address wallet, uint256 class) {
        uint256 tier = _tierOf(tokenId);
        class = _classOf(tokenId);

        if (tier == 4) {
            wallet = red;
        } else if (tier == 3) {
            wallet = yellow;
        } else if (tier == 2) {
            wallet = blue;
        } else if (tier == 1) {
            if (_massOf(tokenId) >= cap) {
                wallet = contender;
            } else {
                wallet = _getWalletByClass(class);

                // No wallet for this class has been created yet.
                if (wallet == address(0)) {
                    wallet = _createWalletByClass(class);
                    require(wallet == _getWalletByClass(class), "Mismatch");
                } else {
                    uint256 _tokenId = _tokenOf(wallet);
                    if (_tokenId != 0) {
                        if (_massOf(_tokenId) >= cap) {  // Current wallet has reached the cap
                            wallet = _createWalletByClass(class);
                            require(wallet == _getWalletByClass(class), "Mismatch");
                        } else {
                            if (_classOf(_tokenId) != class) {
                                wallet = _createWalletByClass(class);
                                require(wallet == _getWalletByClass(class), "Mismatch");
                            }
                        }
                    }
                }
            }
        }
    }
// Solidity 0.8.9
/**
 * @dev Update info for `account` and `tokenId` with `weight`
 */
function _updateInfo(address account, uint256 class, uint256 weight) private {
        if (weights[account][class] == 0) {
            contributors.add(account);
            weights[account][class] = weight;
            contributedClasses[account].push(class);
        } else {
            weights[account][class] += weight;
        }

        totalWeight += weight;
        contributionsOfEachClass[class]++;
    }
// Solidity 0.6.12
/// @notice create new property for Certified Partner
/// @param certifiedPartner Wallet address of Certified Partner
/// @return contract address of newly created property
function createNewPropTokenFor(address certifiedPartner) public returns (address) {
        require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), "PropertiesFactory: You need to have system admin rights to issue new PropToken");
        require(PropertyFactoryHelpers(_dataProxy).isCertifiedPartner(certifiedPartner), "PropertiesFactory: You can only create property for certified partner!");
        Properties propToken = new Properties(certifiedPartner, _propertyRegistry);
        PropertyFactoryHelpers(_dataProxy).addPropertyToCP(address(propToken), certifiedPartner);

        emit NewPropToken(certifiedPartner, address(propToken), now);

        return address(propToken);
    }
// Solidity 0.6.12
/// @notice create new property for Certified Partner and Licenced Issuer
/// @param certifiedPartner Wallet address of Certified Partner
/// @param LI Wallet address of Licenced Issuer
/// @return contract address of newly created property
function createNewPropTokenForCPAndLI(address certifiedPartner, address LI) public returns (address){
        require(PropertyFactoryHelpers(_dataProxy).hasSystemAdminRights(msg.sender), "PropertiesFactory: You need to have system admin rights to issue new PropToken");
        require(PropertyFactoryHelpers(_dataProxy).isCertifiedPartner(certifiedPartner), "PropertiesFactory: You can only create property for certified partner!");
        Properties propToken = new Properties(LI, _propertyRegistry);
        PropertyFactoryHelpers(_dataProxy).addPropertyToCP(address(propToken), certifiedPartner);

        emit NewPropToken(certifiedPartner, address(propToken), now);

        return address(propToken);
    }
// Solidity 0.6.12
/**
 order function
 1. user could order either 1 piece or 10 pieces together
 2. the order process is async, user pay the price and pre-order, 
 the system deliver the orders async after receiving random numbers
 */
function order(uint256 packSize, string memory referralCode) public payable onlyWhenEnabled {
        console.log("operation:order sender:%s value:%s pack:%s", msg.sender, msg.value, packSize);

        require(
            packSize == 1 || packSize == PACK_NUMBER,
            "Invalid pack size"
        );

        require(
            soldNumber + packSize <= MAX_NFT_NUMBER,
            "Max supply reached"
        );

        uint256 price;
        if (packSize == 1) {
            price = getLatestPrice();
        } else {
            price = getLatestPackPrice();
        }
        console.log("price:%s", price, " value:", msg.value);
        require(
            msg.value >= price,
            "Insufficient payment"
        );
        
        bytes32 requestID = _getRandomNumber(soldNumber);
        waitingOrders[requestID] = MintContext(msg.sender, price, packSize);
        soldNumber = soldNumber.safeAdd(packSize);

        // Only for testing
        emit RNGRequest(requestID);

        // refund the overcharge value
        if (msg.value.safeSub(price) > 0) {
            (bool success, ) =
                msg.sender.call{value: msg.value.safeSub(price)}("");
            require(success, "Refund failed");

            console.log("operation:refund user:%s value:%s", msg.sender, msg.value.safeSub(price));
        }

        // pay referral
        _fundReferral(referralCode, price);
    }
// Solidity 0.6.12
/**
 register to the referral program
 */
function registerReferralCode() public {
        string memory code = _genReferral(msg.sender);
        address record = referrals[code];
        require(
            record == address(0x0),
            "Already registered"
        );
        require(
            referralNumber < MAX_REFERRAL_NUMBER,
            "Referral code all sold out"
        );
        referrals[code] = msg.sender;
        referralNumber = referralNumber.safeAdd(1);
        console.log("operation:registerReferralCode sender:", msg.sender, "code:", code);
    }
// Solidity 0.6.12
/**
 getLatestPackPrice: return the price of the next pack mint
 it's the sum price of the next PACK_NUMBER single mints
 throws error if the remaining supply is less than PACK_NUMBER
 */
function getLatestPackPrice() public view returns (uint256) {
        uint256 price = 0;
        for (uint256 i = 1; i <= PACK_NUMBER; i = i.safeAdd(1)) {
            price = price.safeAdd(_getMintPrice(soldNumber.safeAdd(i)));
        }
        price = price.safeMul(PACK_SALE_DISCOUNT).safeDiv(100);
        return price; 
    }
// Solidity 0.6.12
/**
 getReferralCode: return the referral code for the sender if they registered
 */
function getReferralCode() public view returns (string memory) {
        string memory code = _genReferral(msg.sender);
        address recordAddress = referrals[code];
        console.log("operation:getReferralCode sender:", msg.sender, "code:", code);
        require(
            msg.sender == recordAddress,
            "Not registered to the referral program"
        );
        return code;
    }
// Solidity 0.6.12
/**
 _fundReferral: fund price * REFERRAL_CUT% to the referer
 */
function _fundReferral(string memory referralCode, uint256 price) internal {
        address toAddress = referrals[referralCode];
        if (toAddress != address(0x0)) {
            uint256 referralCut = price.safeMul(REFERRAL_CUT).safeDiv(100);
            (bool success, ) = payable(toAddress).call{value: referralCut}("");
            require(success, "Payment to referral failed");
        }
    }
// Solidity 0.6.12
/**
 _mintOne function:
 1. generate the NFT
 */
function _mintOne(address toAddress, uint256 randomness) internal {
        // Check supply
        require(
            mintedNumber < MAX_NFT_NUMBER,
            "Insufficient supply"
        );

        uint256 seedIndex;
        uint256 printIndex;
        (seedIndex, printIndex) = _calc(randomness);
        uint256 score = 1;
        uint256 token = _genToken(toAddress, seedIndex, printIndex, score);
        console.log("minted seedIndex is '%s' printIndex is '%s' token is '%s'", seedIndex, printIndex, token);

        _mint(toAddress, token);
        mintedNumber = mintedNumber.safeAdd(1);
        seedMintedNumber[seedIndex] = seedMintedNumber[seedIndex].safeAdd(1);
    }
// Solidity 0.6.12
/**
 _calc: calculate the seed index and print index from the random number
 */
function _calc(uint256 randomness) internal view returns (uint256, uint256) {
        assert(mintedNumber < MAX_NFT_NUMBER);
        uint256 n = randomness.safeMod(MAX_NFT_NUMBER.safeSub(mintedNumber)).safeAdd(1);
        for (uint256 seedIndex = STARTING_INDEX; seedIndex <= MAX_SEED_NUMBER; seedIndex = seedIndex.safeAdd(1)) {
            uint remainingPrintNumber = MAX_PRINT_NUMBERS[seedIndex].safeSub(seedMintedNumber[seedIndex]);
            if (n <= remainingPrintNumber) {
                uint256 printIndex = seedMintedNumber[seedIndex].safeAdd(1);
                return (seedIndex, printIndex);
            }
            n = n.safeSub(remainingPrintNumber);
        }
        // should not reach here
        assert(false);
    }
// Solidity 0.6.12
/**
 * _genToken generates unique token for each NFT
 *  - 1st byte: seedIndex
 *  - 2nd byte: printIndex
 *  - 3rd byte: score
 *  - 4th byte: zero (reserved byte)
 */
function _genToken(address toAddress, uint256 seedIndex, uint256 printIndex, uint256 score) internal view returns (uint256) {
        bytes32 hash = keccak256(abi.encodePacked(block.number, blockhash(block.number - 1), toAddress, seedIndex, printIndex, score));
        uint256 token = 0;
        for (uint256 i = 0; i < 32; i = i.safeAdd(1)) {
            token = token << 8;
            if (i == 0) {
                token = token | seedIndex;
            } else if (i == 1) {
                token = token | printIndex;
            } else if (i == 2) {
                token = token | score;
            } else if (i == 3) {
                // do nothing, reversed byte
            } else {
                token = token | uint8(hash[i]);
            }
        }
        return token;
    }
// Solidity 0.6.12
/** 
 _getRandomNumber: send the request number request to chain.link
 */
function _getRandomNumber(uint256 seed) internal returns (bytes32) {
        uint256 linkBalance = LINK.balanceOf(address(this));
        require(
            linkBalance >= LINK_FEE, 
            "Contract doesn't have enough LINK"
        );
        console.log("operation:callChainLink seed:%s balance:%s", seed, linkBalance);
        return requestRandomness(KEY_HASH, LINK_FEE, seed);
    }
// Solidity 0.6.12
/**
 return the substring which has length of k
 */
function _substr(string memory _str, uint256 k) internal pure returns (string memory) {
        bytes memory bstr = bytes(_str);
        if (k >= bstr.length) {
            return _str;
        }
        
        bytes memory bsubstr = new bytes(k);
        for (uint i = 0; i < k; i++) {
            bsubstr[i] = bstr[i];
        }
        return string(bsubstr);
    }
// Solidity 0.8.4
/**
 * @dev Request the random number to be used for a batch mint
 */
function requestRandomNumber() external onlyOwner {
    // Can trigger only one randomness request at a time
    require(
      randomNumberStatus != RNStatus.requested,
      "Random number already requested"
    );
    // We need some LINK to pay a fee to the oracles
    require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
    // Indicate that a request has been initiated
    randomNumberStatus = RNStatus.requested;
    // Request a random number to Chainlink oracles
    bytes32 requestId = requestRandomness(keyhash, fee);
    emit RequestedRandomness(requestId);
  }
// Solidity 0.8.4
/**
 * Called by Chainlink oracles when sending back a random number for
 * a given request
 * This function cannot use more than 200,000 gas or the transaction
 * will fail
 */
function fulfillRandomness(bytes32 requestId, uint256 randomNumber)
    internal
    override
  {
    // Put 16 bytes of randomNumber into randomSeed
    randomSeed =
      randomNumber &
      0xffffffffffffffff0000000000000000ffffffffffffffff0000000000000000;
    // Put the other 16 bytes of randomNumber into randomIncrementor
    randomIncrementor =
      randomNumber &
      0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff;
    // We're making sure the random incrementor is high enough and most
    // importantly not zero
    if (randomIncrementor < 10000) {
      randomIncrementor += 10000;
    }
    // Allow to trigger a new randomness request
    randomNumberStatus = RNStatus.received;
    // Just to tell us that the random number has been received
    // No need to broadcast, however making it public is not problematic
    // and shouldn't since any data on-chain is public (even private variable)
    emit RandomNumberReceived(requestId);
  }
// Solidity 0.8.7
/**
 Get NEW TAT2, use approve/transferFrom
 @param amount number of old TAT2
 */
function swap(uint256 amount) external {
        uint8 decimals = newtat2decimals - oldtat2decimals;
        uint256 newamount = amount * (10 ** decimals);
        require(
            INterfaces(oldtat2).transferFrom(msg.sender, address(this), amount),
            ERR_TRANSFER
        );
        require(
            INterfaces(newtat2).transfer(msg.sender, newamount),
            ERR_TRANSFER
        );
        emit Swapped(msg.sender, amount, newamount);
    }