lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.13
/**
 * @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
 * generated by calculating keccak256 of a incremented counter.
 * @param _paramsHash parameters hash
 * @param _proposer address
 * @param _organization address
 */
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
        external
        returns(bytes32)
    {
      // solhint-disable-next-line not-rely-on-time
        require(now > parameters[_paramsHash].activationTime, "not active yet");
        //Check parameters existence.
        require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
        // Generate a unique ID:
        bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
        proposalsCnt = proposalsCnt.add(1);
         // Open proposal:
        Proposal memory proposal;
        proposal.callbacks = msg.sender;
        proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));

        proposal.state = ProposalState.Queued;
        // solhint-disable-next-line not-rely-on-time
        proposal.times[0] = now;//submitted time
        proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
        proposal.proposer = _proposer;
        proposal.winningVote = NO;
        proposal.paramsHash = _paramsHash;
        if (organizations[proposal.organizationId] == address(0)) {
            if (_organization == address(0)) {
                organizations[proposal.organizationId] = msg.sender;
            } else {
                organizations[proposal.organizationId] = _organization;
            }
        }
        //calc dao bounty
        uint256 daoBounty =
        parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
        proposal.daoBountyRemain = daoBounty.max(parameters[_paramsHash].minimumDaoBounty);
        proposals[proposalId] = proposal;
        proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;//dao downstake on the proposal

        emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
        return proposalId;
    }
// Solidity 0.5.13
/**
 * @dev executeBoosted try to execute a boosted or QuietEndingPeriod proposal if it is expired
 * it rewards the msg.sender with P % of the proposal's upstakes upon a successful call to this function.
 * P = t/150, where t is the number of seconds passed since the the proposal's timeout.
 * P is capped by 10%.
 * @param _proposalId the id of the proposal
 * @return uint256 expirationCallBounty the bounty amount for the expiration call
 */
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
        Proposal storage proposal = proposals[_proposalId];
        require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
        "proposal state in not Boosted nor QuietEndingPeriod");
        require(_execute(_proposalId), "proposal need to expire");

        proposal.secondsFromTimeOutTillExecuteBoosted =
        // solhint-disable-next-line not-rely-on-time
        now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1]));

        expirationCallBounty = calcExecuteCallBounty(_proposalId);
        proposal.totalStakes = proposal.totalStakes.sub(expirationCallBounty);
        require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
        emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
    }
// Solidity 0.5.11
/* ============= Contract initialization
 * dev: initializes token: set initial values for erc20 variables
 *      assigns all tokens ('totalSupply') to one address ('tokenOwner')
 * @param _contractNumberInTheLedger Contract Id.
 * @param _description Description of the project of organization (short text or just a link)
 * @param _name Name of the token
 * @param _symbol Symbol of the token
 * @param _tokenOwner Address that will initially hold all created tokens
 * @param _dividendsPeriod Period in seconds between finish of the previous dividends round and start of the next.
 *        On test net can be small.
 * @param _xEurContractAddress Address of contract with xEUR tokens
 *        (can be different for test net, where we use mock up contract)
 * @param _cryptonomicaVerificationContractAddress Address of the Cryptonomica verification smart contract
 *        (can be different for test net, where we use mock up contract)
 * @param _disputeResolutionAgreement Text of the arbitration agreement.
 */
function initToken(
        uint _contractNumberInTheLedger,
        string calldata _description,
        string calldata _name,
        string calldata _symbol,
        uint _dividendsPeriod,
        address _xEurContractAddress,
        address _cryptonomicaVerificationContractAddress,
        string calldata _disputeResolutionAgreement
    ) external returns (bool success) {

        require(
            msg.sender == creator,
            "Only creator can initialize token contract"
        );

        require(
            totalSupply == 0,
            "Contract already initialized"
        );

        contractNumberInTheLedger = _contractNumberInTheLedger;
        description = _description;
        name = _name;
        symbol = _symbol;
        xEuro = XEuro(_xEurContractAddress);
        cryptonomicaVerification = CryptonomicaVerification(_cryptonomicaVerificationContractAddress);
        disputeResolutionAgreement = _disputeResolutionAgreement;
        dividendsPeriod = _dividendsPeriod;

        return true;
    }
// Solidity 0.8.4
/// @notice Compute the virtual liquidity from a position's parameters.
/// @param tickLower The lower tick of a position.
/// @param tickUpper The upper tick of a position.
/// @param liquidity The liquidity of a a position.
/// @dev vLiquidity = liquidity * validRange^2 / 1e6, where the validRange is the tick amount of the
/// intersection between the position and the reward range.
/// We divided it by 1e6 to keep vLiquidity smaller than Q128 in most cases. This is safe since liqudity is usually a large number.
function _getVLiquidityForNFT(
        int24 tickLower,
        int24 tickUpper,
        uint128 liquidity
    ) internal view returns (uint256 vLiquidity) {
        // liquidity is roughly equals to sqrt(amountX*amountY)
        require(liquidity >= 1e6, "LIQUIDITY TOO SMALL");
        uint256 validRange = uint24(
            Math.max(
                Math.min(rewardUpperTick, tickUpper) - Math.max(rewardLowerTick, tickLower),
                0
            )
        );
        vLiquidity = (validRange * validRange * uint256(liquidity)) / 1e6;
        return vLiquidity;
    }
// Solidity 0.5.11
/*
 * @dev initToken and issueTokens are separate functions because of
 * 'Stack too deep' exception from compiler
 * @param _tokenOwner Address that will get all new created tokens.
 * @param _totalSupply Amount of tokens to create.
 */
function issueTokens(
        uint _totalSupply,
        address _tokenOwner
    ) external returns (bool success){

        require(
            msg.sender == creator,
            "Only creator can initialize token contract"
        );

        require(
            totalSupply == 0,
            "Contract already initialized"
        );

        require(
            _totalSupply > 0,
            "Number of tokens can not be zero"
        );


        totalSupply = _totalSupply;

        balanceOf[_tokenOwner] = totalSupply;

        emit Transfer(address(0), _tokenOwner, _totalSupply);

        return true;
    }
// Solidity 0.6.12
// Enter the bar. Pay some 123bs. Earn some shares.
// Locks 123b and mints 123s
function enter(uint256 _amount) public {
        // Gets the amount of 123b locked in the contract
        uint256 total123b = bonus.balanceOf(address(this));
        // Gets the amount of 123s in existence
        uint256 totalShares = totalSupply();
        // If no 123s exists, mint it 1:1 to the amount put in
        if (totalShares == 0 || total123b == 0) {
            _mint(msg.sender, _amount);
        } 
        // Calculate and mint the amount of 123s the 123b is worth. The ratio will change overtime, as 123s is burned/minted and 123b deposited + gained from fees / withdrawn.
        else {
            uint256 what = _amount.mul(totalShares).div(total123b);
            _mint(msg.sender, what);
        }
        // Lock the 123b in the contract
        bonus.transferFrom(msg.sender, address(this), _amount);
    }
// Solidity 0.6.12
// Leave the bar. Claim back your 123b.
// Unlocks the staked + gained 123b and burns 123s
function leave(uint256 _share) public {
        // Gets the amount of 123s in existence
        uint256 totalShares = totalSupply();
        // Calculates the amount of 123b the 123s is worth
        uint256 what = _share.mul(bonus.balanceOf(address(this))).div(totalShares);
        _burn(msg.sender, _share);
        bonus.transfer(msg.sender, what);
    }
// Solidity 0.8.4
/// @notice withdraw a single position.
/// @param tokenId The related position id.
/// @param noReward true if donot collect reward
function withdraw(uint256 tokenId, bool noReward) external nonReentrant {
        require(owners[tokenId] == msg.sender, "NOT OWNER OR NOT EXIST");

        if (noReward) {
            _updateGlobalStatus();
        } else {
            _collectReward(tokenId);
        }
        uint256 vLiquidity = tokenStatus[tokenId].vLiquidity;
        _updateVLiquidity(vLiquidity, false);
        uint256 nIZI = tokenStatus[tokenId].nIZI;
        if (nIZI > 0) {
            _updateNIZI(nIZI, false);
            // refund iZi to user
            iziToken.safeTransfer(msg.sender, nIZI);
        }

        uniV3NFTManager.safeTransferFrom(address(this), msg.sender, tokenId);
        owners[tokenId] = address(0);
        bool res = tokenIds[msg.sender].remove(tokenId);
        require(res);

        emit Withdraw(msg.sender, tokenId);
    }
// Solidity 0.6.11
// emergency withdraw without caring about pending earnings
// pending earnings will be lost / set to 0 if used emergency withdraw
function emergencyWithdraw(uint amountToWithdraw) public {
        require(amountToWithdraw > 0, "Cannot withdraw 0 Tokens");
        require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
        require(now.sub(depositTime[msg.sender]) > cliffTime, "You recently deposited!, please wait before withdrawing.");

        // set pending earnings to 0 here
        lastClaimedTime[msg.sender] = now;
    
        uint fee = amountToWithdraw.mul(withdrawFeePercentX100).div(1e4);
        uint amountAfterFee = amountToWithdraw.sub(fee);
    
        require(Token(trustedDepositTokenAddress).transfer(owner, fee), "Could not transfer fee!");
        require(Token(trustedDepositTokenAddress).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
        
        depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
        
        if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
            holders.remove(msg.sender);
        }
    }
// Solidity 0.6.11
// function to allow admin to claim *other* ERC20 tokens sent to this contract (by mistake)
// Admin cannot transfer out deposit tokens from this smart contract
// Admin can transfer out reward tokens from this address once adminClaimableTime has reached
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
        require(_tokenAddr != trustedDepositTokenAddress, "Admin cannot transfer out Deposit Tokens from this contract!");
        
        require((_tokenAddr != trustedRewardTokenAddress) || (now > adminClaimableTime), "Admin cannot Transfer out Reward Tokens yet!");
        
        Token(_tokenAddr).transfer(_to, _amount);
    }
// Solidity 0.5.11
/**
 * @param _newAdmin Address of new admin
 */
function addAdmin(address _newAdmin) public onlyAdmin returns (bool success){

        require(
            cryptonomicaVerification.keyCertificateValidUntil(_newAdmin) > now,
            "New admin has to be verified on Cryptonomica.net"
        );

        // revokedOn returns uint256 (unix time), it's 0 if verification is not revoked
        require(
            cryptonomicaVerification.revokedOn(_newAdmin) == 0,
            "Verification for this address was revoked, can not add"
        );

        isAdmin[_newAdmin] = true;

        emit AdminAdded(_newAdmin, msg.sender);

        return true;
    }
// Solidity 0.6.12
// Deposit LP tokens to OneTwoThreeMasterChef for BONUS 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.accBonusPerShare).div(1e12).sub(
                    user.rewardDebt
                );
            safeBonusTransfer(msg.sender, pending);
        }
        pool.lpToken.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );
        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.6.12
// Withdraw LP tokens from OneTwoThreeMasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        uint256 pending =
            user.amount.mul(pool.accBonusPerShare).div(1e12).sub(
                user.rewardDebt
            );
        safeBonusTransfer(msg.sender, pending);
        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }
// Solidity 0.6.11
/**
 * @notice Get all view URIs for all nfts inside a given montage.
 * @param _tokenId the id of a previously minted Montage NFT
 * @return metadata the off-chain URIs to view the token metadata of each token in json format
 */
function viewURIsInMontage(uint256 _tokenId)
        public
        override
        view
        onlyExistingTokens(_tokenId)
        returns (string memory metadata)
    {
        uint256[] memory tokenIds = getTokenIds(_tokenId);
        uint256 len = tokenIds.length;

        // start JSON object
        metadata = strConcat("{\n", '  "uris": [\n');

        // transfer ownership of nfts to this contract
        for (uint256 i = 0; i < len; i++) {
            // Media URI
            metadata = strConcat(metadata, '"');
            metadata = strConcat(metadata, erc721Contract.tokenURI(tokenIds[i]));
            metadata = strConcat(metadata, '"');
            if (i < len - 1) {
                metadata = strConcat(metadata, ", ");
            }
        }
        //close array
        metadata = strConcat(metadata, "\n  ]");

        // Finish JSON object
        metadata = strConcat(metadata, "\n}");
    }
// Solidity 0.6.11
/*
 * unpacks the montage, transferring ownership of the individual nfts inside the montage to the montage owner before burning the montage nft
 */
function unpackMontage(uint256 _tokenId) external override onlyTokenOwner(_tokenId) {
        require(canBeUnpacked(_tokenId), "unpackMontage: cannot unpack this montage");
        uint256[] memory tokenIds = getTokenIds(_tokenId);

        uint256 len = tokenIds.length;
        // transfer ownership of nfts from this contract to the sender address
        for (uint256 i = 0; i < len; i++) {
            erc721Contract.transferFrom(address(this), msg.sender, tokenIds[i]);
        }

        _burn(_tokenId);
        emit MontageUnpacked(_tokenId);
    }
// Solidity 0.8.10
/**
 * @notice Mint single token
 * @param beneficiary This address will receive the token
 * @param mintCode Can be anything, but it affects the token code, which will also affect image id
 */
function mint(address beneficiary, bytes32 mintCode) external payable {
        require(block.timestamp >= mintStart, "mint not started");
        require(block.timestamp <= mintEnd, "mint finished");
        require(msg.value == mintFee, "wrong mint fee");
        require(totalSupply() < mintLimit, "mint limit exceed");

        _mintInternal(beneficiary, mintCode);
    }
// Solidity 0.7.6
/**
 * @notice Mint a new Voucher of the specified type.
 * @param term_ Release term:
 *              One-time release type: fixed at 0;
 *              Linear and Staged release type: duration in seconds from start to end of release.
 * @param amount_ Amount of assets (ERC20) to be locked up
 * @param maturities_ Timestamp of each release time node
 * @param percentages_ Release percentage of each release time node
 * @param originalInvestor_ Note indicating the original invester
 */
function mint(
        uint64 term_, /*seconds*/
        uint256 amount_,
        uint64[] calldata maturities_,
        uint32[] calldata percentages_,
        string memory originalInvestor_
    ) external virtual override returns (uint256, uint256) {
        (uint256 slot, uint256 tokenId) = _mint(
            msg.sender,
            term_,
            amount_,
            maturities_,
            percentages_,
            originalInvestor_
        );
        return (slot, tokenId);
    }
// Solidity 0.8.10
/**
 * @notice Mint multiple tokens
 * @param beneficiaries List of addresses which will receive tokens
 * @param mintCodes List of mint codes (also see mint() function)
 */
function bulkMint(address[] calldata beneficiaries, bytes32[] calldata mintCodes) external payable {
        require(block.timestamp >= mintStart, "mint not started");
        require(block.timestamp <= mintEnd, "mint finished");
        uint256 count = beneficiaries.length;
        require(mintCodes.length == count, "array length mismatch");
        require(msg.value == mintFee * count, "wrong mint fee");
        require(totalSupply() + count <= mintLimit, "mint limit exceed");

        for (uint256 i = 0; i < count; i++) {
            _mintInternal(beneficiaries[i], mintCodes[i]);
        }
    }
// Solidity 0.4.26
// function GetTreeByUserId(uint32 UserId, bool report) view public returns (User[]){
//     //Get Position
//     uint32 userposition = uint32(userlistbyid[uint32(UserId)].Position);
//     //Try to return all data base on position
//     uint userCount = 0;
//     if(report){
//         userCount = uint((2 ** (uint(currentLevel) + 1)) - 1);
//     }
//     else{
//         userCount = 15;
//     }
//     User[] memory userlist = new User[](userCount);
//     uint counter = 0;
//     uint32 availablenodes = 2;
//     int8 userlevel = 2;
//     userlist[counter] = userlistbyid[uint32(userlistbypos[userposition].Id)];
//     counter++;
//     while(true){
//         userposition = userposition * 2;
//         for(uint32 i = 0; i < availablenodes; i++){
//             userlist[counter] = userlistbyid[uint32(userlistbypos[userposition + i].Id)];
//             counter++;
//         }
//         availablenodes = availablenodes * 2;
//         userlevel++;
//         if(report == false){
//             if(availablenodes > 8){
//                 break;
//             }
//         }
//         else{
//             if(userlevel > currentLevel){
//                 break;
//             }
//         }
//     }
//     return userlist;
// }
// function GetUserById(uint32 userId) view public returns(User user){
//     user = userlistbyid[userId];
// }
function CheckInvestmentExpiry() public onlyOwner{
        require(!isContractAlive(), "Contract is alive.");
        require(PayoutAmount == 0, "Contract balance is already calculated.");
        
        if(MainterPayoutAmount != 0){
            PayoutMaintainer();
        }
        
        //Current Date - last Investment Date >= 365 days from last investment date timestamp
        if(!isContractAlive()){
            IsExpired = true;
            uint contractBalance = ERC20Interface.balanceOf(address(this));
            PayoutAmount = uint(contractBalance / uint(UnpaidUserCount));
        }
    }
// Solidity 0.8.10
/**
 * @notice Calculates image id
 * @param id Token id
 */
function imageId(uint256 id) public view returns (bytes32) {
        if (imageSalt == bytes32(0)) {
            // Images are not revealed yet
            return bytes32(0);
        }
        bytes32 tokenCode = tokenCodes[id];
        if (tokenCode == bytes32(0)) return bytes32(0); // Non-existing token
        return keccak256(abi.encodePacked(imageSalt, tokenCode));
    }
// Solidity 0.4.25
/**
 * Constructor function
 *
 * Initializes contract
 */
function Opacity() public payable {
    director = msg.sender;
    name = "Opacity";
    symbol = "OPQ";
    decimals = 18;
    directorLock = false;
    funds = 0;
    totalSupply = 130000000 * 10 ** uint256(decimals);

    // Assign reserved OPQ supply to the director
    balances[director] = totalSupply;

    // Define default values for Opacity functions
    claimAmount = 5 * 10 ** (uint256(decimals) - 1);
    payAmount = 4 * 10 ** (uint256(decimals) - 1);
    feeAmount = 1 * 10 ** (uint256(decimals) - 1);

    // Seconds in a year
    epoch = 31536000;

    // Maximum time for a sector to remain stored
    retentionMax = 40 * 10 ** uint256(decimals);
  }
// Solidity 0.4.25
/**
 * Director can alter the storage-peg and broker fees
 */
function amendClaim(uint8 claimAmountSet, uint8 payAmountSet, uint8 feeAmountSet, uint8 accuracy) public onlyDirector returns (bool success) {
    require(claimAmountSet == (payAmountSet + feeAmountSet));
    require(payAmountSet < claimAmountSet);
    require(feeAmountSet < claimAmountSet);
    require(claimAmountSet > 0);
    require(payAmountSet > 0);
    require(feeAmountSet > 0);

    claimAmount = claimAmountSet * 10 ** (uint256(decimals) - accuracy);
    payAmount = payAmountSet * 10 ** (uint256(decimals) - accuracy);
    feeAmount = feeAmountSet * 10 ** (uint256(decimals) - accuracy);
    return true;
  }
// Solidity 0.4.25
/**
 * Bury an address
 *
 * When an address is buried; only claimAmount can be withdrawn once per epoch
 */
function bury() public returns (bool success) {
    // The address must be previously unburied
    require(!buried[msg.sender]);

    // An address must have at least claimAmount to be buried
    require(balances[msg.sender] >= claimAmount);

    // Prevent addresses with large balances from getting buried
    require(balances[msg.sender] <= retentionMax);

    // Set buried state to true
    buried[msg.sender] = true;

    // Set the initial claim clock to 1
    claimed[msg.sender] = 1;

    // Execute an event reflecting the change
    emit Bury(msg.sender, balances[msg.sender]);
    return true;
  }
// Solidity 0.5.16
/// @dev Return the entitied LP token balance for the given shares.
/// @param share The number of shares to be converted to LP balance.
function shareToBalance(uint256 share) public view returns (uint256) {
        if (totalShare == 0) return share; // When there's no share, 1 share = 1 balance.
        uint256 totalBalance = staking.balanceOf(address(this));
        return share.mul(totalBalance).div(totalShare);
    }
// Solidity 0.5.16
/// @dev Return the number of shares to receive if staking the given LP tokens.
/// @param balance the number of LP tokens to be converted to shares.
function balanceToShare(uint256 balance) public view returns (uint256) {
        if (totalShare == 0) return balance; // When there's no share, 1 share = 1 balance.
        uint256 totalBalance = staking.balanceOf(address(this));
        return balance.mul(totalShare).div(totalBalance);
    }