lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.12
/**
 * @dev Calculates the additional stars per share that have been accumulated
 * since lastRewardBlock, and updates accStarsPerShare and lastRewardBlock
 * accordingly.
 */
function updatePool(uint256 _pid) public isInitialized {
        PoolInfo storage pool = poolInfo[_pid];
        if (block.number <= pool.lastRewardBlock) {
            return;
        }
        if (pool.poolSupply != 0) {
            uint256 currRateEndStarsPerShare =
                accStarsPerShareAtCurrRate(
                    uint256(block.number).sub(startBlock),
                    pool.poolSupply
                );
            uint256 currRateStartStarsPerShare =
                accStarsPerShareAtCurrRate(
                    pool.lastRewardBlock.sub(startBlock),
                    pool.poolSupply
                );
            uint256 starsReward =
                (currRateEndStarsPerShare.sub(currRateStartStarsPerShare))
                    .mul(pool.allocPoint)
                    .div(totalAllocPoint);

            pool.accStarsPerShare = pool.accStarsPerShare.add(starsReward);
        }
        pool.lastRewardBlock = block.number;
    }
// Solidity 0.6.12
/**
 * @dev Collect rewards owed.
 *
 * Params:
 * _pid: the pool id
 */
function collectRewards(uint256 _pid) public isInitialized {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);

        if (user.amount > 0) {
            uint256 pending =
                user.amount.mul(pool.accStarsPerShare).div(1e12).sub(
                    user.rewardDebt
                );
            safeStarsTransfer(msg.sender, pending);
            user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);
        }

        emit RewardsCollected(msg.sender, _pid);
    }
// Solidity 0.6.12
/**
 * @dev Deposit stars for staking. The sender's pending rewards are
 * sent to the sender, and the sender's information is updated accordingly.
 *
 * Params:
 * _pid: the pool id
 * _amount: amount of Stars to deposit
 */
function deposit(uint256 _pid, uint256 _amount) public isInitialized {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        updatePool(_pid);
        pool.lpToken.safeTransferFrom(
            address(msg.sender),
            address(this),
            _amount
        );

        uint256 pending =
            user.amount.mul(pool.accStarsPerShare).div(1e12).sub(
                user.rewardDebt
            );
        safeStarsTransfer(msg.sender, pending);

        user.amount = user.amount.add(_amount);
        user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);
        pool.poolSupply = pool.poolSupply.add(_amount);
        emit Deposit(msg.sender, _pid, _amount);
    }
// Solidity 0.6.12
/**
 * @dev Withdraw Stars from the amount that the user is staking and collect
 * pending rewards.
 *
 * Params:
 * _pid: the pool id
 * _amount: amount of Stars to withdraw
 *
 * Requirements:
 * _amount is less than or equal to the amount of Stars the the user has
 * deposited to the contract
 */
function withdraw(uint256 _pid, uint256 _amount) public isInitialized {
        PoolInfo storage pool = poolInfo[_pid];
        UserInfo storage user = userInfo[_pid][msg.sender];
        require(user.amount >= _amount, "withdraw: not good");
        updatePool(_pid);
        pool.lpToken.safeTransfer(address(msg.sender), _amount);

        uint256 pending =
            user.amount.mul(pool.accStarsPerShare).div(1e12).sub(
                user.rewardDebt
            );
        safeStarsTransfer(msg.sender, pending);

        user.amount = user.amount.sub(_amount);
        user.rewardDebt = user.amount.mul(pool.accStarsPerShare).div(1e12);
        pool.poolSupply = pool.poolSupply.sub(_amount);
        emit Withdraw(msg.sender, _pid, _amount);
    }
// Solidity 0.4.21
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
        if (_tokenId == 1) {
            buffer[0] = "Hello World! :D";
            count = 15;
        } else if (_tokenId == 2) {
            buffer[0] = "I would definitely choose a medi";
            buffer[1] = "um length string.";
            count = 49;
        } else if (_tokenId == 3) {
            buffer[0] = "Lorem ipsum dolor sit amet, mi e";
            buffer[1] = "st accumsan dapibus augue lorem,";
            buffer[2] = " tristique vestibulum id, libero";
            buffer[3] = " suscipit varius sapien aliquam.";
            count = 128;
        }
    }
// Solidity 0.4.21
/// @dev Remove all Ether from the contract, which is the owner's cuts
///  as well as any Ether sent directly to the contract address.
///  Always transfers to the NFT contract, but can be called either by
///  the owner or the NFT contract.
function withdrawBalance() external {
        address nftAddress = address(nonFungibleContract);

        require(
            msg.sender == owner ||
            msg.sender == nftAddress
        );
        // We are using this boolean method to make sure that even if one fails it will still work
        bool res = nftAddress.send(this.balance);
    }
// Solidity 0.4.21
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) external view returns (
        address seller,
        uint256 startingPrice,
        uint256 endingPrice,
        uint256 duration,
        uint256 startedAt
    ) {
        Auction storage auction = tokenIdToAuction[_tokenId];
        require(_isOnAuction(auction));
        return (
            auction.seller,
            auction.startingPrice,
            auction.endingPrice,
            auction.duration,
            auction.startedAt
        );
    }
// Solidity 0.4.21
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
        uint256 _tokenId,
        uint256 _startingPrice,
        uint256 _endingPrice,
        uint256 _duration,
        address _seller
    )
        external
    {
        // Sanity check that no inputs overflow how many bits we've allocated
        // to store them in the auction struct.
        require(_startingPrice == uint256(uint128(_startingPrice)));
        require(_endingPrice == uint256(uint128(_endingPrice)));
        require(_duration == uint256(uint64(_duration)));
        require(msg.sender == address(nonFungibleContract));

        _escrow(_seller, _tokenId);
        Auction memory auction = Auction(
            _seller,
            uint128(_startingPrice),
            uint128(_endingPrice),
            uint64(_duration),
            uint64(now)
        );
        _addAuction(_tokenId, auction);
    }
// Solidity 0.4.21
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
        external
        payable
    {
        // _bid verifies token ID size
        address seller = tokenIdToAuction[_tokenId].seller;
        uint256 price = _bid(_tokenId, msg.value);
        _transfer(msg.sender, _tokenId);

        // If not a gen0 auction, exit
        if (seller == address(nonFungibleContract)) {
            // Track gen0 sale prices
            lastArtworkSalePrices[artworkSaleCount % 5] = price;
            value += price;
            artworkSaleCount++;
        }
    }
// Solidity 0.4.21
//Creates a unique key based on the artwork name, author, and series
function getUniqueKey(string name, string author, uint32 _version)  internal pure returns(bytes32) {
        string memory version = _uintToString(_version);
        string memory main = _strConcat(name, author, version, "$%)");
        string memory lowercased = _toLower(main);
        return keccak256(lowercased);
    }
// Solidity 0.4.21
//https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97
//transform to lowercase
function _toLower(string str) internal pure returns (string)  {
		bytes memory bStr = bytes(str);
		bytes memory bLower = new bytes(bStr.length);
		for (uint i = 0; i < bStr.length; i++) {
			// Uppercase character...
			if ((bStr[i] >= 65) && (bStr[i] <= 90)) {
				// So we add 32 to make it lowercase
				bLower[i] = bytes1(int(bStr[i]) + 32);
			} else {
				bLower[i] = bStr[i];
			}
		}
		return string(bLower);
	}
// Solidity 0.4.21
//creates a unique key from all variables
function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) {
        bytes memory _ba = bytes(_a);
        bytes memory _bb = bytes(_separator);
        bytes memory _bc = bytes(_b);
        bytes memory _bd = bytes(_separator);
        bytes memory _be = bytes(_c);
        string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
        bytes memory babcde = bytes(abcde);
        uint k = 0;
        for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
        for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
        for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
        for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
        for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
        return string(babcde);
    }
// Solidity 0.4.21
/// title String Utils - String utility functions
/// @author Piper Merriam - <pipermerriam@gmail.com>
///https://github.com/pipermerriam/ethereum-string-utils
function _uintToBytes(uint v) private pure returns (bytes32 ret) {
        if (v == 0) {
            ret = "0";
        } else {
            while (v > 0) {
                ret = bytes32(uint(ret) / (2 ** 8));
                ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
                v /= 10;
            }
        }
        return ret;
    }
// Solidity 0.4.21
/// @notice Grant another address the right to transfer a specific Artwork via
///  transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
///  clear all approvals.
/// @param _tokenId The ID of the Artwork that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
        address _to,
        uint256 _tokenId
    )
        external
        whenNotPaused
    {
        // Only an owner can grant transfer approval.
        require(_owns(msg.sender, _tokenId));

        // Register the approval (replacing any previous approval).
        _approve(_tokenId, _to);

        // Emit approval event.
        Approval(msg.sender, _to, _tokenId);
    }
// Solidity 0.4.21
/// @notice Transfer a Artwork owned by another address, for which the calling address
///  has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Artwork to be transfered.
/// @param _to The address that should take ownership of the Artwork. Can be any address,
///  including the caller.
/// @param _tokenId The ID of the Artwork to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
        address _from,
        address _to,
        uint256 _tokenId
    )
        external
        whenNotPaused
    {
        // Safety check to prevent against an unexpected 0x0 default.
        require(_to != address(0));
        // Disallow transfers to this contract to prevent accidental misuse.
        // The contract should never own any artworks (except very briefly
        // after a artwork is created and before it goes on auction).
        require(_to != address(this));
        // Check for approval and valid ownership
        require(_approvedFor(msg.sender, _tokenId));
        require(_owns(_from, _tokenId));

        // Reassign ownership (also clears pending approvals and emits Transfer event).
        _transfer(_from, _to, _tokenId);
    }
// Solidity 0.4.21
/// @notice Transfers a Artwork to another address. If transferring to a smart
///  contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
///  CryptoArtworks specifically) or your Artwork may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Artwork to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _tokenId) external whenNotPaused {

        // Safety check to prevent against an unexpected 0x0 default.
        require(_to != address(0));

        // Disallow transfers to this contract to prevent accidental misuse.
        // The contract should never own any Artworks (except very briefly
        // after a  artwork is created and before it goes on auction).
        require(_to != address(this));

        // Disallow transfers to the auction contracts to prevent accidental
        // misuse. Auction contracts should only take ownership of artworks
        // through the allow + transferFrom flow.
        require(_to != address(saleAuction));

        // You can only send your own artwork.
        require(_owns(msg.sender, _tokenId));

        // Reassign ownership, clear pending approvals, emit Transfer event.
        _transfer(msg.sender, _to, _tokenId);

    }
// Solidity 0.4.21
/// @notice Returns a list of all Artwork IDs assigned to an address.
/// @param _owner The owner whose Artworks we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
///  expensive (it walks the entire Artwork array looking for arts belonging to owner),
///  but it also returns a dynamic array, which is only supported for web3 calls, and
///  not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
        uint256 tokenCount = balanceOf(_owner);

        if (tokenCount == 0) {
            // Return an empty array
            return new uint256[](0);
        } else {
            uint256[] memory result = new uint256[](tokenCount);
            uint256 totalArts = totalSupply();
            uint256 resultIndex = 0;

            // We count on the fact that all arts have IDs starting at 1 and increasing
            // sequentially up to the totalArt count.
            uint256 artworkId;

            for (artworkId = 1; artworkId <= totalArts; artworkId++) {
                if (artworkIndexToOwner[artworkId] == _owner) {
                    result[resultIndex] = artworkId;
                    resultIndex++;
                }
            }

            return result;
        }
    }
// Solidity 0.4.21
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <arachnid@notdot.net>)
///  This method is licenced under the Apache License.
///  Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
        // Copy word-length chunks while possible
        for (; _len >= 32; _len -= 32) {
            assembly {
                mstore(_dest, mload(_src))
            }
            _dest += 32;
            _src += 32;
        }

        // Copy remaining bytes
        uint256 mask = 256 ** (32 - _len) - 1;
        assembly {
            let srcpart := and(mload(_src), not(mask))
            let destpart := and(mload(_dest), mask)
            mstore(_dest, or(destpart, srcpart))
        }
    }
// Solidity 0.4.21
/// @dev Put a artwork up for auction.
///  Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
        uint256 _artworkId,
        uint256 _startingPrice,
        uint256 _endingPrice,
        uint256 _duration
    )
        external
        whenNotPaused
    {
        // Auction contract checks input sizes
        // If artwork is already on any auction, this will throw
        // because it will be owned by the auction contract.
        require(_owns(msg.sender, _artworkId));
        _approve(_artworkId, saleAuction);
        // Sale auction throws if inputs are invalid and clears
        // transfer and sire approval after escrowing the artwork.
        saleAuction.createAuction(
            _artworkId,
            _startingPrice,
            _endingPrice,
            _duration,
            msg.sender
        );
    }
// Solidity 0.4.21
/// @dev we can create promo artworks, up to a limit. Only callable by COO
/// @param _owner the future owner of the created artworks. Default to contract COO
function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO {
        bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
        (require(!uniqueArtworks[uniqueKey]));
        if (_series != 0) {
            bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
            (require(!uniqueArtworks[uniqueKeyForZero]));
        }
        address artworkOwner = _owner;
        if (artworkOwner == address(0)) {
            artworkOwner = cooAddress;
        }
        require(promoCreatedCount < PROMO_CREATION_LIMIT);

        promoCreatedCount++;
        _createArtwork(_name, _author, _series, artworkOwner);
        uniqueArtworks[uniqueKey] = true;
    }
// Solidity 0.4.21
/// @dev Creates a new artwork with the given name and author and
///  creates an auction for it.
function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO {
        bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
        (require(!uniqueArtworks[uniqueKey]));
        require(artsCreatedCount < CREATION_LIMIT);
        if (_series != 0) {
            bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
            (require(!uniqueArtworks[uniqueKeyForZero]));
        }
        uint256 artworkId = _createArtwork(_name, _author, _series, address(this));
        _approve(artworkId, saleAuction);
        uint256 price = _computeNextArtworkPrice();
        saleAuction.createAuction(
            artworkId,
            price,
            0,
            ARTWORK_AUCTION_DURATION,
            address(this)
        );
        artsCreatedCount++;
        uniqueArtworks[uniqueKey] = true;
    }
// Solidity 0.4.21
/// @dev Computes the next gen0 auction starting price, given
///  the average of the past 5 prices + 50%.
function _computeNextArtworkPrice() internal view returns (uint256) {
        uint256 avePrice = saleAuction.averageArtworkSalePrice();

        // Sanity check to ensure we don't overflow arithmetic
        require(avePrice == uint256(uint128(avePrice)));

        uint256 nextPrice = avePrice + (avePrice / 2);

        // We never auction for less than starting price
        if (nextPrice < ARTWORK_STARTING_PRICE) {
            nextPrice = ARTWORK_STARTING_PRICE;
        }

        return nextPrice;
    }
// Solidity 0.4.21
/// @notice Creates the main CryptoArtworks smart contract instance.
function ArtworkCore() public {
        // Starts paused.
        paused = true;

        // the creator of the contract is the initial CEO
        ceoAddress = msg.sender;

        // the creator of the contract is also the initial COO
        cooAddress = msg.sender;

        // start with the art
        _createArtwork("none", "none", 0, address(0));
    }
// Solidity 0.4.21
/// @notice Returns all the relevant information about a specific artwork.
/// @param _id The ID of the artwork of interest.
function getArtwork(uint256 _id)
        external
        view
        returns (
        uint256 birthTime,
        string name,
        string author,
        uint32 series
    ) {
        Artwork storage art = artworks[_id];
        birthTime = uint256(art.birthTime);
        name = string(art.name);
        author = string(art.author);
        series = uint32(art.series);
    }
// Solidity 0.6.6
/**
 * @param solidBondID is a solid bond ID
 * @param SBTAmount is solid bond token amount
 * @return poolID is a pool ID
 * @return IDOLAmount is iDOL amount obtained
 */
function _swapSBT2IDOL(
        bytes32 solidBondID,
        address SBTAddress,
        uint256 SBTAmount
    ) internal returns (bytes32 poolID, uint256 IDOLAmount) {
        // 1. approve
        ERC20(SBTAddress).approve(address(_IDOLContract), SBTAmount);

        // 2. mint (SBT -> iDOL)
        (poolID, IDOLAmount, ) = _IDOLContract.mint(
            solidBondID,
            msg.sender,
            SBTAmount.toUint64()
        );

        emit LogIssueIDOL(solidBondID, msg.sender, poolID, IDOLAmount);
        return (poolID, IDOLAmount);
    }
// Solidity 0.6.6
/**
 * @notice swap (LBT -> iDOL)
 * @param LBTAddress is liquid bond token contract address
 * @param LBTAmount is liquid bond amount
 * @param timeout (uniswap)
 * @param isLimit (uniswap)
 */
function _swapLBT2IDOL(
        address LBTAddress,
        uint256 LBTAmount,
        uint256 timeout,
        bool isLimit
    ) internal isNotEmptyExchangeInstance {
        address _boxExchangeAddress = _exchangeLBTAndIDOLFactoryContract
            .addressToExchangeLookup(LBTAddress);
        // 1. approve
        ERC20(LBTAddress).approve(_boxExchangeAddress, LBTAmount);

        // 2. order(exchange)
        BoxExchangeInterface exchange = BoxExchangeInterface(
            _boxExchangeAddress
        );
        exchange.orderSettlementToBase(timeout, msg.sender, LBTAmount, isLimit);
    }
// Solidity 0.6.6
/**
 * @notice swap (SBT -> LBT)
 * @param solidBondID is a solid bond ID
 * @param liquidBondID is a liquid bond ID
 * @param timeout (uniswap)
 * @param isLimit (uniswap)
 */
function swapSBT2LBT(
        bytes32 solidBondID,
        bytes32 liquidBondID,
        uint256 SBTAmount,
        uint256 timeout,
        bool isLimit
    ) public override {
        (address SBTAddress, , , ) = _bondMakerContract.getBond(solidBondID);
        require(SBTAddress != address(0), "the bond is not registered");

        // uses: SBT
        _usesERC20(SBTAddress, SBTAmount);

        // 1. SBT -> LBT(exchange)
        _swapSBT2LBT(
            solidBondID,
            SBTAddress,
            liquidBondID,
            SBTAmount,
            timeout,
            isLimit
        );
    }
// Solidity 0.6.6
/**
 * @notice find a solid bond in given bond group
 * @param bondGroupID is a bond group ID
 */
function _findSBTAndLBTBondGroup(uint256 bondGroupID)
        internal
        view
        returns (bytes32 solidBondID, bytes32[] memory liquidBondIDs)
    {
        (bytes32[] memory bondIDs, ) = _bondMakerContract.getBondGroup(
            bondGroupID
        );
        bytes32 solidID = bytes32(0);
        bytes32[] memory liquidIDs = new bytes32[](bondIDs.length - 1);
        uint256 j = 0;
        for (uint256 i = 0; i < bondIDs.length; i++) {
            (, , uint256 solidStrikePrice, ) = _bondMakerContract.getBond(
                bondIDs[i]
            );
            if (solidStrikePrice != 0) {
                // A solid bond is found.
                solidID = bondIDs[i];
            } else {
                liquidIDs[j++] = bondIDs[i];
            }
        }
        return (solidID, liquidIDs);
    }