lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.19
// ------------------------------------------------------------------------
// ecrecover from a signature rather than the signature in parts [v, r, s]
// The signature format is a compact form {bytes32 r}{bytes32 s}{uint8 v}.
// Compact means, uint8 is not padded to 32 bytes.
//
// An invalid signature results in the address(0) being returned, make
// sure that the returned result is checked to be non-zero for validity
//
// Parts from https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
// ------------------------------------------------------------------------
function ecrecoverFromSig(bytes32 hash, bytes sig) public pure returns (address recoveredAddress) {
        bytes32 r;
        bytes32 s;
        uint8 v;
        if (sig.length != 65) return address(0);
        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            // Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread.
            // There is no 'mload8' to do this, but that would be nicer.
            v := byte(0, mload(add(sig, 96)))
        }
        // Albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28]
        // geth uses [0, 1] and some clients have followed. This might change, see https://github.com/ethereum/go-ethereum/issues/2053
        if (v < 27) {
          v += 27;
        }
        if (v != 27 && v != 28) return address(0);
        return ecrecover(hash, v, r, s);
    }
// Solidity 0.4.19
// ------------------------------------------------------------------------
// Get CheckResult message
// ------------------------------------------------------------------------
function getCheckResultMessage(Data storage /*self*/, BTTSTokenInterface.CheckResult result) public pure returns (string) {
        if (result == BTTSTokenInterface.CheckResult.Success) {
            return "Success";
        } else if (result == BTTSTokenInterface.CheckResult.NotTransferable) {
            return "Tokens not transferable yet";
        } else if (result == BTTSTokenInterface.CheckResult.AccountLocked) {
            return "Account locked";
        } else if (result == BTTSTokenInterface.CheckResult.SignerMismatch) {
            return "Mismatch in signing account";
        } else if (result == BTTSTokenInterface.CheckResult.InvalidNonce) {
            return "Invalid nonce";
        } else if (result == BTTSTokenInterface.CheckResult.InsufficientApprovedTokens) {
            return "Insufficient approved tokens";
        } else if (result == BTTSTokenInterface.CheckResult.InsufficientApprovedTokensForFees) {
            return "Insufficient approved tokens for fees";
        } else if (result == BTTSTokenInterface.CheckResult.InsufficientTokens) {
            return "Insufficient tokens";
        } else if (result == BTTSTokenInterface.CheckResult.InsufficientTokensForFees) {
            return "Insufficient tokens for fees";
        } else if (result == BTTSTokenInterface.CheckResult.OverflowError) {
            return "Overflow error";
        } else {
            return "Unknown error";
        }
    }
// Solidity 0.4.19
// ------------------------------------------------------------------------
// Token functions
// ------------------------------------------------------------------------
function transfer(Data storage self, address to, uint tokens) public returns (bool success) {
        // Owner and minter can move tokens before the tokens are transferable
        require(self.transferable || (self.mintable && (msg.sender == self.owner  || msg.sender == self.minter)));
        require(!self.accountLocked[msg.sender]);
        self.balances[msg.sender] = safeSub(self.balances[msg.sender], tokens);
        self.balances[to] = safeAdd(self.balances[to], tokens);
        Transfer(msg.sender, to, tokens);
        return true;
    }
// Solidity 0.4.19
// ------------------------------------------------------------------------
// Anyone can call this method to verify whether the bttsToken contract at
// the specified address was deployed using this factory
//
// Parameters:
//   tokenContract  the bttsToken contract address
//
// Return values:
//   valid          did this BTTSTokenFactory create the BTTSToken contract?
//   decimals       number of decimal places for the token contract
//   initialSupply  the token initial supply
//   mintable       is the token mintable after deployment?
//   transferable   are the tokens transferable after deployment?
// ------------------------------------------------------------------------
function verify(address tokenContract) public view returns (
        bool    valid,
        address owner,
        uint    decimals,
        bool    mintable,
        bool    transferable
    ) {
        valid = _verify[tokenContract];
        if (valid) {
            BTTSToken t = BTTSToken(tokenContract);
            owner        = t.owner();
            decimals     = t.decimals();
            mintable     = t.mintable();
            transferable = t.transferable();
        }
    }
// Solidity 0.4.19
// ------------------------------------------------------------------------
// Any account can call this method to deploy a new BTTSToken contract.
// The owner of the BTTSToken contract will be the calling account
//
// Parameters:
//   symbol         symbol
//   name           name
//   decimals       number of decimal places for the token contract
//   initialSupply  the token initial supply
//   mintable       is the token mintable after deployment?
//   transferable   are the tokens transferable after deployment?
//
// For example, deploying a BTTSToken contract with `initialSupply` of
// 1,000.000000000000000000 tokens:
//   symbol         "ME"
//   name           "My Token"
//   decimals       18
//   initialSupply  10000000000000000000000 = 1,000.000000000000000000
//                  tokens
//   mintable       can tokens be minted after deployment?
//   transferable   are the tokens transferable after deployment?
//
// The BTTSTokenListing() event is logged with the following parameters
//   owner          the account that execute this transaction
//   symbol         symbol
//   name           name
//   decimals       number of decimal places for the token contract
//   initialSupply  the token initial supply
//   mintable       can tokens be minted after deployment?
//   transferable   are the tokens transferable after deployment?
// ------------------------------------------------------------------------
function deployBTTSTokenContract(
        string symbol,
        string name,
        uint8 decimals,
        uint initialSupply,
        bool mintable,
        bool transferable
    ) public returns (address bttsTokenAddress) {
        bttsTokenAddress = new BTTSToken(
            msg.sender,
            symbol,
            name,
            decimals,
            initialSupply,
            mintable,
            transferable);
        // Record that this factory created the trader
        _verify[bttsTokenAddress] = true;
        deployedTokens.push(bttsTokenAddress);
        BTTSTokenListing(msg.sender, bttsTokenAddress, symbol, name, decimals,
            initialSupply, mintable, transferable);
    }
// Solidity 0.4.24
/**
 * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
 * Transfer event.
 * @param _from The address of the sender.
 * @param _to The address of the recipient.
 * @param _value The amount of token to be transferred.
 */
function transferFrom(
    address _from,
    address _to,
    uint256 _value
  )
    public
    returns (bool _success)
  {
    require(_value <= balances[_from]);
    require(_value <= allowed[_from][msg.sender]);

    balances[_from] = balances[_from].sub(_value);
    balances[_to] = balances[_to].add(_value);
    allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);

    emit Transfer(_from, _to, _value);
    _success = true;
  }
// Solidity 0.4.20
/*
 This function allows users to purchase Video Game. 
 The price is automatically multiplied by 2 after each purchase.
 Users can purchase multiple video games.
 */
function purchaseVideoGame(uint _videoGameId) public payable {
        require(msg.value == videoGames[_videoGameId].currentPrice);
        require(isPaused == false);

        // Calculate the 10% value
        uint256 devFee = (msg.value / 10);

        // Calculate the video game owner commission on this sale & transfer the commission to the owner.     
        uint256 commissionOwner = msg.value - devFee; // => 90%
        videoGames[_videoGameId].ownerAddress.transfer(commissionOwner);

        // Transfer the 10% commission to the developer
        devFeeAddress.transfer(devFee); // => 10%                       

        // Update the video game owner and set the new price
        videoGames[_videoGameId].ownerAddress = msg.sender;
        videoGames[_videoGameId].currentPrice = mul(videoGames[_videoGameId].currentPrice, 2);
    }
// Solidity 0.4.18
/// @notice Returns all the relevant information about a specific color.
/// @param _tokenId The tokenId of the color of interest.
function getColor(uint256 _tokenId) public view returns (
    string colorName,
    uint256 sellingPrice,
    address owner,
    uint256 previousPrice,
    address[5] previousOwners
  ) {
    Color storage color = colors[_tokenId];
    colorName = color.name;
    sellingPrice = colorIndexToPrice[_tokenId];
    owner = colorIndexToOwner[_tokenId];
    previousPrice = colorIndexToPreviousPrice[_tokenId];
    previousOwners = colorIndexToPreviousOwners[_tokenId];
  }
// Solidity 0.4.18
/// For creating Color
function _createColor(string _name, address _owner, uint256 _price) private {
    Color memory _color = Color({
      name: _name
    });
    uint256 newColorId = colors.push(_color) - 1;

    // It's probably never going to happen, 4 billion tokens are A LOT, but
    // let's just be 100% sure we never let this happen.
    require(newColorId == uint256(uint32(newColorId)));

    Birth(newColorId, _name, _owner);

    colorIndexToPrice[newColorId] = _price;
    colorIndexToPreviousPrice[newColorId] = 0;
    colorIndexToPreviousOwners[newColorId] =
        [address(this), address(this), address(this), address(this), address(this)];

    // This will assign ownership, and also emit the Transfer event as
    // per ERC721 draft
    _transfer(address(0), _owner, newColorId);
  }
// Solidity 0.7.0
// Reduce some liquidity - use to enhance pump effectiveness during bull run!
function createLiquidityCrisis()
        external
        payable
        override
    {
        require (block.timestamp >= minLiquidityCrisisTime, "It's too early to create a liquidity crisis");
        require (msg.sender == owner || msg.value >= 100 ether, "This can only be called by paying 100 ETH");

        minLiquidityCrisisTime = block.timestamp + 60 * 60 * 24 * 90; // No more for 3 months;

        uint256 liquidity = initialLiquidityTokens / 4;
        uint256 balance = uniswapEthUppPair.balanceOf(address(this));
        if (liquidity > balance) { liquidity = balance; }
        if (liquidity == 0) { return; }

        uniswapEthUppPair.approve(address(uniswapV2Router), liquidity);
        (uint256 amountToken,) = uniswapV2Router.removeLiquidityETH(
            address(this),
            liquidity,
            0,
            0,
            owner,
            block.timestamp);

        _transfer(owner, address(this), amountToken);
        _approve(address(this), address(staking), amountToken);
        staking.increaseRewardsPot();

        emit LiquidityCrisis();
    }
// Solidity 0.8.0
/// @dev Creates a new random number
function newRandomNumber(uint256 id, bytes32 fileHash)
        public
        onlyOperators()
        nonZeroId(id)
        idMustBeUnique(id)
        nonZeroFileHash(fileHash)
        hashMustBeUnique(fileHash)
    {
        randomNumbers[id].id = id;
        randomNumbers[id].fileHash = fileHash;

        emit NewRandomNumber(id, fileHash);

        hashToId[fileHash] = id;
        lastId = id;
        numberOfRandomNumbers += 1;
    }
// Solidity 0.8.0
/// @dev Bulk creation to reduce gas fees.
function bulkRandomNumbers(
        uint256[] memory ids,
        bytes32[] memory fileHashes
    ) public onlyOperators() {
        require(
            ids.length == fileHashes.length,
            "Arrays must be the same length"
        );

        for (uint256 i = 0; i < ids.length; i++) {
            newRandomNumber(ids[i], fileHashes[i]);
        }
    }
// Solidity 0.8.0
/// @dev Generate the random number
function generateRandomNumber(uint256 id)
        public
        onlyOperators()
        nonZeroId(id)
        idMustExists(id)
    {
        require(
            randomNumbers[id].requestId == 0,
            "Request already exists for this ID."
        );
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
        bytes32 requestId = requestRandomness(keyHash, fee);
        randomNumbers[id].requestId = requestId;
        requestIdToId[requestId] = id;
    }
// Solidity 0.8.0
/// @dev Generate the random numbers
function bulkGenerateRandomNumbers(uint256[] memory ids)
        public
        onlyOperators()
    {
        require(
            LINK.balanceOf(address(this)) >= fee * ids.length,
            "Not enough LINK"
        );

        for (uint256 i = 0; i < ids.length; i++) {
            require(ids[i] != 0, "ID cannot be 0");
            require(randomNumbers[ids[i]].fileHash != 0, "ID does not exists");
            require(
                randomNumbers[ids[i]].requestId == 0,
                "Request already exists for this ID."
            );

            bytes32 requestId = requestRandomness(keyHash, fee);
            randomNumbers[ids[i]].requestId = requestId;
            requestIdToId[requestId] = ids[i];
        }
    }
// Solidity 0.4.23
/**
 * Passes execution into virtual function.
 *
 * Can only be called by assigned asset proxy.
 *
 * @return success.
 * @dev function is final, and must not be overridden.
 */
function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyProxy() returns(bool) {
        if (isICAP(_to)) {
            return _transferFromToICAPWithReference(_from, bytes32(_to) << 96, _value, _reference, _sender);
        }
        return _transferFromWithReference(_from, _to, _value, _reference, _sender);
    }
// Solidity 0.4.20
/// For creating Pow
function _createPow(string _name, address _owner, uint256 _price, uint _gameId, uint _gameItemId) private {
    Pow memory _pow = Pow({
      name: _name,
      gameId: _gameId,
      gameItemId: _gameItemId
    });
    uint256 newPowId = pows.push(_pow) - 1;

    // It's probably never going to happen, 4 billion tokens are A LOT, but
    // let's just be 100% sure we never let this happen.
    require(newPowId == uint256(uint32(newPowId)));

    Birth(newPowId, _name, _owner);

    powIndexToPrice[newPowId] = _price;

    // This will assign ownership, and also emit the Transfer event as
    // per ERC721 draft
    _transfer(address(0), _owner, newPowId);
  }
// Solidity 0.4.20
/// @dev Assigns ownership of a specific Pow to an address.
function _transfer(address _from, address _to, uint256 _tokenId) private {
    // Since the number of pow is capped to 2^32 we can't overflow this
    ownershipTokenCount[_to]++;
    //transfer ownership
    powIndexToOwner[_tokenId] = _to;

    // When creating new pows _from is 0x0, but we can't account that address.
    if (_from != address(0)) {
      ownershipTokenCount[_from]--;
      // clear any previously approved ownership exchange
      delete powIndexToApproved[_tokenId];
    }

    // Emit the transfer event.
    Transfer(_from, _to, _tokenId);
  }
// Solidity 0.8.7
/* GET FUNCTIONS */
function getGemStone(uint256 p_tokenId) public view returns (string memory) {
        require(_exists(p_tokenId),"Not minted");           
        uint256 gemId = findGemId(p_tokenId, "GEMSTONE");
        string[8] memory gemStoneNames = [
            "Blue Diamond",
            "Pink Diamond",
            "Diamond",
            "Ruby",
            "Emerald",
            "Sapphire",            
            "Jade",
            "Opal"
        ];
        return gemStoneNames[gemId];
    }
// Solidity 0.8.7
// FINDER functions
// Find Gem Id can find anything from an array with 8 elements (note: weighting table in place)
function findGemId(uint256 p_tokenId, string memory p_seedString) internal view returns (uint256) {
        uint8[8] memory weightings = [
            1,
            2,
            4,
            8,
            16,
            32,
            56,
            78
        ];
        uint256 rand = random(abi.encodePacked(p_seedString, s_randomSeeds[p_tokenId]));
        uint256 weighting = (rand % 100)+1;
        uint256 r_attrId = weightings.length-1;
        for (uint i=0; i<weightings.length-1; i++) {
            if (weighting>=weightings[i] && weighting<weightings[i+1]) {
                r_attrId = i;
            }
        }
        return r_attrId;
    }
// Solidity 0.8.7
// Find Gem Power can find anything from an array with 13 elements (note: weighting table in place)
function findGemPowerId(uint256 p_tokenId, string memory p_seedPhrase) internal view returns (uint256) {
         uint8[13] memory weightings = [
            1,
            4,
            7,
            10,
            15,
            20,
            25,
            30,
            45,
            55,
            65,
            75,
            85
        ];
        uint256 rand = random(abi.encodePacked(p_seedPhrase, s_randomSeeds[p_tokenId]));
        uint256 weighting = (rand % 100)+1;
        uint256 r_attrId = weightings.length-1;
        for (uint i=0; i<weightings.length-1; i++) {
            if (weighting>=weightings[i] && weighting<weightings[i+1]) {
                r_attrId = i;
            }
        }
        return r_attrId;
    }
// Solidity 0.8.7
// Loot minting (free)
function mintWithLoot(uint p_lootId) public payable nonReentrant {
        require(lootContract.ownerOf(p_lootId) == msg.sender, "Not loot owner");
        _safeMint(msg.sender, p_lootId);
        s_randomSeeds[p_lootId] = uint256(blockhash(block.number - 2))
            ^ block.timestamp
            ^ block.difficulty 
            ^ p_lootId
            ^ block.basefee
            ^ uint256(keccak256(abi.encodePacked(block.coinbase)));
    }
// Solidity 0.8.7
// Owner reserved minting (100 items)
function ownerMint(uint p_tokenId) public payable nonReentrant onlyOwner {
         require(p_tokenId > 12000 && p_tokenId <= 12100, "Token ID invalid");
        _safeMint(msg.sender, p_tokenId);         
        s_randomSeeds[p_tokenId] =  uint256(blockhash(block.number - 2))
            ^ block.timestamp
            ^ block.difficulty
            ^ p_tokenId
            ^ block.basefee
            ^ uint256(keccak256(abi.encodePacked(block.coinbase)));
        
     }
// Solidity 0.8.0
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners() public view returns (address[] memory) {
        uint256 len = EnumerableSet.length(_owners);
        address[] memory o = new address[](len);

        for (uint256 i = 0; i < len; i++) {
            o[i] = EnumerableSet.at(_owners, i);
        }

        return o;
    }
// Solidity 0.8.0
/// @dev Helper function to fail if resolution number is already in use.
function resolutionAlreadyUsed(uint256 resNum) public view {
        require(
            // atleast one of the address must not be equal to address(0)
            !(resolutions[resNum].oldAddress != address(0) ||
                resolutions[resNum].newAddress != address(0)),
            "Resolution is already in use."
        );
    }
// Solidity 0.8.0
/// @notice Vote Yes on a Resolution.
/// @dev The owner who tips the agreement threshold will pay the gas for performing the resolution.
/// @return TRUE if the resolution passed
function voteResolution(uint256 resNum) public onlyOwners() returns (bool) {
        ownerVotes[msg.sender][resNum] = true;

        // If the reolution has already passed, then do nothing
        if (isResolutionPassed(resNum)) {
            return true;
        }

        // If the resolution can now be passed, then do so
        if (canResolutionPass(resNum)) {
            _performResolution(resNum);
            return true;
        }

        // The resolution cannot be passed yet
        return false;
    }
// Solidity 0.8.0
/// @dev Create a resolution to repalce an owner. Performs replacement if threshold is 1 or zero.
function createResolutionReplaceOwner(address oldOwner, address newOwner)
        public
        onlyOwners()
    {
        isValidAddress(oldOwner);
        isValidAddress(newOwner);
        require(
            EnumerableSet.contains(_owners, oldOwner),
            "oldOwner is not an owner."
        );
        require(
            !EnumerableSet.contains(_owners, newOwner),
            "newOwner already exists."
        );

        createResolution(resTypeReplaceOwner, oldOwner, newOwner, new bytes32[](0));
    }
// Solidity 0.8.0
/// @dev Create a resolution to replace the operator account. Performs replacement if threshold is 1 or zero.
function createResolutionReplaceOperator(
        address oldOperator,
        address newOperator
    ) public onlyOwners() {
        isValidAddress(oldOperator);
        isValidAddress(newOperator);
        require(
            EnumerableSet.contains(_operators, oldOperator),
            "oldOperator is not an Operator."
        );
        require(
            !EnumerableSet.contains(_operators, newOperator),
            "newOperator already exists."
        );

        createResolution(resTypeReplaceOperator, oldOperator, newOperator,new bytes32[](0));
    }
// Solidity 0.8.0
/// @dev Create a resolution and check if we can call perofrm the resolution with 1 vote.
function createResolution(
        uint256 resType,
        address oldAddress,
        address newAddress,
        bytes32[] memory extra
    ) internal {
        uint256 resNum = nextResolution;
        nextResolution++;
        resolutionAlreadyUsed(resNum);

        resolutions[resNum].resType = resType;
        resolutions[resNum].oldAddress = oldAddress;
        resolutions[resNum].newAddress = newAddress;
        resolutions[resNum].extra = extra;

        ownerVotes[msg.sender][resNum] = true;
        lastOwnerResolutionNumber[msg.sender] = resNum;

        // Check if agreement is already reached
        if (ownerAgreementThreshold <= 1) {
            _performResolution(resNum);
        }
    }