lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.9
/**
 * @dev Returns the address that signed a hashed message (`hash`) with
 * `signature` or error string. This address can then be used for verification purposes.
 *
 * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
 * this function rejects them by requiring the `s` value to be in the lower
 * half order, and the `v` value to be either 27 or 28.
 *
 * IMPORTANT: `hash` _must_ be the result of a hash operation for the
 * verification to be secure: it is possible to craft signatures that
 * recover to arbitrary addresses for non-hashed data. A safe way to ensure
 * this is by receiving a hash of the original message (which may otherwise
 * be too long), and then calling {toEthSignedMessageHash} on it.
 *
 * Documentation for signature generation:
 * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
 * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
 *
 * _Available since v4.3._
 */
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }
// Solidity 0.8.9
/**
 * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
 *
 * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
 *
 * _Available since v4.3._
 */
function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s;
        uint8 v;
        assembly {
            s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
            v := add(shr(255, vs), 27)
        }
        return tryRecover(hash, v, r, s);
    }
// Solidity 0.8.7
/**
 * @dev Gets the value of the bits between left and right, both inclusive, in the given integer.
 *      31 is the leftmost bit, 0 is the rightmost bit.
 *      
 *      For example: bitsFrom(10, 3, 1) == 7 (101 in binary), because 10 is *101*0 in binary
 *                   bitsFrom(10, 2, 0) == 2 (010 in binary), because 10 is 1*010* in binary
 */
function bitsFrom(uint integer, uint left, uint right) external pure returns (uint) {
        require(left >= right, "left > right");
        require(left <= 31, "left > 31");

        uint delta = left - right + 1;

        return (integer & (((1 << delta) - 1) << right)) >> right;
    }
// Solidity 0.8.7
/**
 * @dev Copies a string into `dst` starting at `dstIndex` with a maximum length of `dstLen`.
 *      This function will not write beyond `dstLen`. However, if `dstLen` is not reached, it may write zeros beyond the length of the string.
 */
function copyString(string memory src, bytes memory dst, uint dstIndex, uint dstLen) internal pure returns (uint) {
        uint srcIndex;
        uint srcLen = bytes(src).length;

        for (; srcLen > 31 && srcIndex < srcLen && srcIndex < dstLen - 31; srcIndex += 32) {
            memcpy32(src, srcIndex, dst, dstIndex + srcIndex);
        }
        for (; srcIndex < srcLen && srcIndex < dstLen; ++srcIndex) {
            memcpy1(src, srcIndex, dst, dstIndex + srcIndex);
        }

        return dstIndex + srcLen;
    }
// Solidity 0.8.7
/**
 * @dev Adds `str` to the end of the internal buffer.
 */
function pushToStringBuffer(StringBuffer memory self, string memory str) internal pure returns (StringBuffer memory) {
        if (self.buffer.length == self.numberOfStrings) {
            string[] memory newBuffer = new string[](self.buffer.length * 2);
            for (uint i = 0; i < self.buffer.length; ++i) {
                newBuffer[i] = self.buffer[i];
            }
            self.buffer = newBuffer;
        }

        self.buffer[self.numberOfStrings] = str;
        self.numberOfStrings++;
        self.totalStringLength += bytes(str).length;

        return self;
    }
// Solidity 0.8.7
/**
 * @dev Concatenates `str` to the end of the last string in the internal buffer.
 */
function concatToLastString(StringBuffer memory self, string memory str) internal pure {
        if (self.numberOfStrings == 0) {
            self.numberOfStrings++;
        }
        uint idx = self.numberOfStrings - 1;
        self.buffer[idx] = string(abi.encodePacked(self.buffer[idx], str));

        self.totalStringLength += bytes(str).length;
    }
// Solidity 0.8.7
/**
 * @notice Converts the contents of the StringBuffer into a string.
 * @dev This runs in O(n) time.
 */
function get(StringBuffer memory self) internal pure returns (string memory) {
        bytes memory output = new bytes(self.totalStringLength);

        uint ptr = 0;
        for (uint i = 0; i < self.numberOfStrings; ++i) {
            ptr = copyString(self.buffer[i], output, ptr, self.totalStringLength);
        }

        return string(output);
    }
// Solidity 0.8.7
/**
 * @notice Appends a string to the end of the StringBuffer
 * @dev Internally the StringBuffer keeps a `string[]` that doubles in size when extra capacity is needed.
 */
function append(StringBuffer memory self, string memory str) internal pure {
        uint idx = self.numberOfStrings == 0 ? 0 : self.numberOfStrings - 1;
        if (bytes(self.buffer[idx]).length + bytes(str).length <= 1024) {
            concatToLastString(self, str);
        } else {
            pushToStringBuffer(self, str);
        }
    }
// Solidity 0.4.24
/**
 * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar
 * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership
 */
function initialize(ENSSubdomainRegistrar _registrar) public onlyInit {
        initialized();

        registrar = _registrar;
        ens = registrar.ens();

        registrar.pointRootNode(this);

        // Check APM has all permissions it needss
        ACL acl = ACL(kernel().acl());
        require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS);
        require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS);
    }
// Solidity 0.8.7
/**
 * Claims all Brainz from all staked Bit Monsters the caller owns.
 */
function claimBrainz() external {
        uint count = bitMonsters.balanceOf(msg.sender);
        uint total = 0;

        for (uint i = 0; i < count; ++i) {
            uint tokenId = bitMonsters.tokenOfOwnerByIndex(msg.sender, i);
            uint rewards = calculateRewards(tokenId);
            if (rewards > 0) {
                tokenIdToTimestamp[tokenId] = block.timestamp - ((block.timestamp - tokenIdToTimestamp[tokenId]) % 86400);
            }
            total += rewards;
        }

        _mint(msg.sender, total);
    }
// Solidity 0.8.7
/**
 * Stake your Brainz a-la OSRS Duel Arena.
 *
 * 50% chance of multiplying your Brainz by 1.9x rounded up.
 * 50% chance of losing everything you stake.
 */
function stake(uint count) external returns (bool won) {
        require(count > 0, "Must stake at least one BRAINZ");
        require(balanceOf(msg.sender) >= count, "You don't have that many tokens");

        Rng memory rn = rng;

        if (rn.generate(0, 1) == 0) {
            _mint(msg.sender, (count - count / 10) * 1 ether);
            won = true;
        }
        else {
            _burn(msg.sender, count * 1 ether);
            won = false;
        }

        rng = rn;
    }
// Solidity 0.4.20
// n: node id  d: direction  r: return node id
// Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, uint n)
        internal
        constant returns (bool)
    {
        if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD)
            return true;
        if (n == HEAD)
            return false;
        if (self.cll[HEAD][NEXT] == n)
            return true;
        return false;
    }
// Solidity 0.4.20
// Can be used before `insert` to build an ordered list
// `a` an existing node to search from, e.g. HEAD.
// `b` value to seek
// `r` first node beyond `b` in direction `d`
function seek(CLL storage self, uint a, uint b, bool d)
        internal  constant returns (uint r)
    {
        r = step(self, a, d);
        while  ((b!=r) && ((b < r) != d)) r = self.cll[r][d];
        return;
    }
// Solidity 0.4.24
/**
 * @notice Create new repo in registry with `_name` and first repo version
 * @param _name Repo name
 * @param _dev Address that will be given permission to create versions
 * @param _initialSemanticVersion Semantic version for new repo version
 * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
 * @param _contentURI External URI for fetching new version's content
 */
function newRepoWithVersion(
        string _name,
        address _dev,
        uint16[3] _initialSemanticVersion,
        address _contractAddress,
        bytes _contentURI
    ) public auth(CREATE_REPO_ROLE) returns (Repo)
    {
        Repo repo = _newRepo(_name, this); // need to have permissions to create version
        repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI);

        // Give permissions to _dev
        ACL acl = ACL(kernel().acl());
        acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE());
        acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE());
        acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE());
        return repo;
    }
// Solidity 0.4.24
/**
 * @notice Create new version for repo
 * @param _newSemanticVersion Semantic version for new repo version
 * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress)
 * @param _contentURI External URI for fetching new version's content
 */
function newVersion(
        uint16[3] _newSemanticVersion,
        address _contractAddress,
        bytes _contentURI
    ) public auth(CREATE_VERSION_ROLE)
    {
        address contractAddress = _contractAddress;
        uint256 lastVersionIndex = versionsNextIndex - 1;

        uint16[3] memory lastSematicVersion;

        if (lastVersionIndex > 0) {
            Version storage lastVersion = versions[lastVersionIndex];
            lastSematicVersion = lastVersion.semanticVersion;

            if (contractAddress == address(0)) {
                contractAddress = lastVersion.contractAddress;
            }
            // Only allows smart contract change on major version bumps
            require(
                lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0],
                ERROR_INVALID_VERSION
            );
        }

        require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP);

        uint256 versionId = versionsNextIndex++;
        versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI);
        versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId;
        latestVersionIdForContract[contractAddress] = versionId;

        emit NewVersion(versionId, _newSemanticVersion);
    }
// Solidity 0.8.4
//  https://ipfs.tokemaklabs.xyz/ipfs/Qmf5Vuy7x5t3rMCa6u57hF8AE89KLNkjdxSKjL8USALwYo/0x4eff3562075c5d2d9cb608139ec2fe86907005fa.json
function claimRewards(
        uint256 cycle,
        uint256 amount,
        uint8 v,
        bytes32 r,
        bytes32 s // bytes calldata signature
    ) external whenNotPaused {
        ITokemakRewards.Recipient memory recipient = ITokemakRewards.Recipient(
            1, // chainId
            cycle,
            address(this), // wallet
            amount
        );

        ITokemakRewards(rewards).claim(recipient, v, r, s);

        emit ClaimRewards(
          msg.sender,
          address(TOKE_TOKEN_ADDRESS),
          address(this),
          amount
        );
    }
// Solidity 0.4.20
/// Constructor initializes the contract
///@param initialSupply Initial supply of tokens
///@param tokenName Display name if the token
///@param tokenSymbol Token symbol
///@param decimalUnits Number of decimal points for token holding display
///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round 
function AquaToken(uint256 initialSupply, 
            string tokenName, 
            string tokenSymbol, 
            uint8 decimalUnits,
            uint8 _redemptionPercentageOfDistribution,
            address _priceOracle
    ) public
    {
        totalSupplyOfTokens = initialSupply;
        holdings.add(msg.sender, LibHoldings.Holding({
            totalTokens : initialSupply, 
            lockedTokens : 0,
            lastRewardNumber : 0,
            weiBalance : 0 
        }));

        name = tokenName;                         // Set the name for display purposes
        symbol = tokenSymbol;                     // Set the symbol for display purposes
        decimals = decimalUnits;                  // Amount of decimals for display purposes
    
        redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution;
    
        priceOracle = AquaPriceOracle(_priceOracle);
        owner = msg.sender;
        
        tokenStatus = TokenStatus.OnSale;
        rewards.push(0);
    }
// Solidity 0.4.20
///Token holders can call this function to request to redeem (sell back to 
///the company) part or all of their tokens
///@param _numberOfTokens Number of tokens to redeem
///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) {
        require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0);
        LibHoldings.Holding storage h = holdings.get(msg.sender);
        require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens);                 // Check if the sender has enough

        uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens);

        h.lockedTokens = h.lockedTokens.add(_numberOfTokens);
        RequestRedemption(msg.sender, _numberOfTokens, redemptionId);
        return redemptionId;
    }
// Solidity 0.4.20
///Token holders can call this function to cancel a redemption request they 
///previously submitted using requestRedemption function
///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public {
        require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId));
        LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId); 
        require(r.holderAddress == msg.sender);

        LibHoldings.Holding storage h = holdings.get(msg.sender); 
        h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens);
        uint numberOfTokens = r.numberOfTokens;
        redemptionsQueue.remove(_requestId);

        CancelRedemptionRequest(msg.sender, numberOfTokens,  _requestId);
    }
// Solidity 0.4.20
///The function returns token holder details given token holder account address
///@param _holder Account address of a token holder
///@return totalTokens Total tokens held by this token holder
///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed
///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant 
            returns (uint totalTokens, uint lockedTokens, uint weiBalance) {
        if (!holdings.exists(_holder)) {
            totalTokens = 0;
            lockedTokens = 0;
            weiBalance = 0;
            return;
        }
        LibHoldings.Holding storage h = holdings.get(_holder);
        totalTokens = h.totalTokens;
        lockedTokens = h.lockedTokens;
        uint stepsMade;
        (weiBalance, stepsMade) = calcFullWeiBalance(h, 0);
        return;
    }
// Solidity 0.4.20
///Token owner calls this function to progress profit distribution round
///@param maxNumbeOfSteps Maximum number of steps in this progression
///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) {
        require(tokenStatus == TokenStatus.Distributing);
        if (continueRedeeming(maxNumbeOfSteps)) {
            ContinueDistribution(true);
            return true;
        }
        uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens );
        rewards.push(tokenReward);
        uint paidReward = tokenReward.mul(totalSupplyOfTokens);


        uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward);
        if (unusedDistributionAmount > 0) {
            if (!holdings.exists(owner)) { 
                holdings.add(owner, LibHoldings.Holding({
                    totalTokens : 0, 
                    lockedTokens : 0,
                    lastRewardNumber : rewards.length.sub(1),
                    weiBalance : unusedDistributionAmount 
                }));
            }
            else {
                LibHoldings.Holding storage ownerHolding = holdings.get(owner);
                ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount);
            }
        }
        tokenStatus = TokenStatus.Trading;
        DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount), 
                            paidReward, unusedDistributionAmount);
        ContinueDistribution(false);
        return false;
    }
// Solidity 0.4.20
///Token holder can call this function to withdraw their balance (dividend 
///and redemption payments) while limiting the number of operations (in the
///extremely unlikely case  when withdrawBalance function exceeds gas limit)
///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public {
        require(holdings.exists(msg.sender));
        LibHoldings.Holding storage h = holdings.get(msg.sender); 
        uint updatedBalance;
        uint stepsMade;
        (updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps);
        h.weiBalance = 0;
        h.lastRewardNumber = h.lastRewardNumber.add(stepsMade);
        
        bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1);
        if (h.totalTokens == 0 && h.weiBalance == 0) 
            holdings.remove(msg.sender);

        msg.sender.transfer(updatedBalance);
        
        WithdrawBalance(msg.sender, updatedBalance, balanceRemainig);
    }
// Solidity 0.4.20
///Token holders can call this method to permanently destroy their tokens.
///WARNING: Burned tokens cannot be recovered!
///@param numberOfTokens Number of tokens to burn (permanently destroy)
///@return True if operation succeeds 
function burn(uint256 numberOfTokens) external returns (bool success) {
        require(holdings.exists(msg.sender));
        if (numberOfTokens == 0) {
            Burn(msg.sender, numberOfTokens);
            return true;
        }
        LibHoldings.Holding storage fromHolding = holdings.get(msg.sender);
        require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens);                 // Check if the sender has enough

        updateWeiBalance(fromHolding, 0);    
        fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens);                         // Subtract from the sender
        if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0) 
            holdings.remove(msg.sender);
        totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens);

        Burn(msg.sender, numberOfTokens);
        return true;
    }
// Solidity 0.4.20
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable {
        require(tokenStatus == TokenStatus.Trading);
        tokenStatus = TokenStatus.WindingUp;
        uint totalWindUpAmount = msg.value;
    
        uint tokenReward = msg.value.div(totalSupplyOfTokens);
        rewards.push(tokenReward);
        uint paidReward = tokenReward.mul(totalSupplyOfTokens);

        uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward);
        if (unusedWindUpAmount > 0) {
            if (!holdings.exists(owner)) { 
                holdings.add(owner, LibHoldings.Holding({
                    totalTokens : 0, 
                    lockedTokens : 0,
                    lastRewardNumber : rewards.length.sub(1),
                    weiBalance : unusedWindUpAmount 
                }));
            }
            else {
                LibHoldings.Holding storage ownerHolding = holdings.get(owner);
                ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount);
            }
        }
        WindingUpStarted(msg.value);
    }
// Solidity 0.8.7
/**
 * Generates a random Bit Monster.
 *
 * 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has.
 * All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted.
 * The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range.
 */
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) {
        uint count = bitMonsters.totalSupply();

        int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10);
        if (ub < 0) {
            ub = 0;
        }

        BitMonster memory m;
        if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) {
            m = BitMonsterGen.generateSpecialBitMonster(rn, ms);
        }
        else {
            m = BitMonsterGen.generateUnspecialBitMonster(rn);
        }

        if (m.special != Special.NONE) {
            mintedSpecialsCount++;
        }
        rng = rn;
        return m;
    }