lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.24
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
        // We do our own memory management here. Solidity uses memory offset
        // 0x40 to store the current end of memory. We write past it (as
        // writes are memory extensions), but don't update the offset so
        // Solidity will reuse it. The memory used here is only needed for
        // this context.

        // FIXME: inline assembly can't access return values
        bool ret;
        address addr;

        assembly {
            let size := mload(0x40)
            mstore(size, hash)
            mstore(add(size, 32), v)
            mstore(add(size, 64), r)
            mstore(add(size, 96), s)

            // NOTE: we can reuse the request memory because we deal with
            //       the return code
            ret := call(3000, 1, 0, size, 128, size, 32)
            addr := mload(size)
        }

        return (ret, addr);
    }
// Solidity 0.5.17
/**
 	 * Hook on `transfer` and call `Withdraw.beforeBalanceChange` function.
 	 */
function transfer(address _to, uint256 _value) public returns (bool) {
		/**
		 * Validates the destination is not 0 address.
		 */
		require(_to != address(0), "this is illegal address");
		require(_value != 0, "illegal transfer value");

		/**
		 * Calls Withdraw contract via Allocator contract.
		 * Passing through the Allocator contract is due to the historical reason for the old Property contract.
		 */
		IAllocator(config().allocator()).beforeBalanceChange(
			address(this),
			msg.sender,
			_to
		);

		/**
		 * Calls the transfer of ERC20.
		 */
		_transfer(msg.sender, _to, _value);
		return true;
	}
// Solidity 0.5.17
/**
 	 * Hook on `transferFrom` and call `Withdraw.beforeBalanceChange` function.
 	 */
function transferFrom(
		address _from,
		address _to,
		uint256 _value
	) public returns (bool) {
		/**
		 * Validates the source and destination is not 0 address.
		 */
		require(_from != address(0), "this is illegal address");
		require(_to != address(0), "this is illegal address");
		require(_value != 0, "illegal transfer value");

		/**
		 * Calls Withdraw contract via Allocator contract.
		 * Passing through the Allocator contract is due to the historical reason for the old Property contract.
		 */
		IAllocator(config().allocator()).beforeBalanceChange(
			address(this),
			_from,
			_to
		);

		/**
		 * Calls the transfer of ERC20.
		 */
		_transfer(_from, _to, _value);

		/**
		 * Reduces the allowance amount.
		 */
		uint256 allowanceAmount = allowance(_from, msg.sender);
		_approve(
			_from,
			msg.sender,
			allowanceAmount.sub(
				_value,
				"ERC20: transfer amount exceeds allowance"
			)
		);
		return true;
	}
// Solidity 0.5.17
/**
 	 * Transfers the staking amount to the original owner.
 	 */
function withdraw(address _sender, uint256 _value) external {
		/**
		 * Validates the sender is Lockup contract.
		 */
		require(msg.sender == config().lockup(), "this is illegal address");

		/**
		 * Transfers the passed amount to the original owner.
		 */
		ERC20 devToken = ERC20(config().token());
		bool result = devToken.transfer(_sender, _value);
		require(result, "dev transfer failed");
	}
// Solidity 0.4.15
/**
 * Sets EToken2 address, assigns symbol and name.
 *
 * Can be set only once.
 *
 * @param _etoken2 EToken2 contract address.
 * @param _symbol assigned symbol.
 * @param _name assigned name.
 *
 * @return success.
 */
function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) {
        if (address(etoken2) != 0x0) {
            return false;
        }
        etoken2 = _etoken2;
        etoken2Symbol = _bytes32(_symbol);
        name = _name;
        symbol = _symbol;
        return true;
    }
// Solidity 0.4.15
/**
 * Propose next asset implementation contract address.
 *
 * Can only be called by current asset owner.
 *
 * Note: freeze-time should not be applied for the initial setup.
 *
 * @param _newVersion asset implementation contract address.
 *
 * @return success.
 */
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
        // Should not already be in the upgrading process.
        if (pendingVersion != 0x0) {
            return false;
        }
        // New version address should be other than 0x0.
        if (_newVersion == 0x0) {
            return false;
        }
        // Don't apply freeze-time for the initial setup.
        if (latestVersion == 0x0) {
            latestVersion = _newVersion;
            return true;
        }
        pendingVersion = _newVersion;
        pendingVersionTimestamp = now;
        UpgradeProposal(_newVersion);
        return true;
    }
// Solidity 0.4.15
/**
 * Finalize an upgrade process setting new asset implementation contract address.
 *
 * Can only be called after an upgrade freeze-time.
 *
 * @return success.
 */
function commitUpgrade() returns(bool) {
        if (pendingVersion == 0x0) {
            return false;
        }
        if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
            return false;
        }
        latestVersion = pendingVersion;
        delete pendingVersion;
        delete pendingVersionTimestamp;
        return true;
    }
// Solidity 0.5.0
/*
 * @dev Returns a newly allocated string containing the concatenation of
 *      `self` and `other`.
 * @param self The first slice to concatenate.
 * @param other The second slice to concatenate.
 * @return The concatenation of the two strings.
 */
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
        string memory ret = new string(self._len + other._len);
        uint retptr;
        assembly {
            retptr := add(ret, 32)
        }
        memcpy(retptr, self._ptr, self._len);
        memcpy(retptr + self._len, other._ptr, other._len);
        return ret;
    }
// Solidity 0.7.6
// SCALE-encode payload
function encodeCall(
        address _token,
        address _sender,
        bytes32 _recipient,
        uint256 _amount
    ) private pure returns (bytes memory) {
        return
            abi.encodePacked(
                MINT_CALL,
                _token,
                _sender,
                byte(0x00), // Encode recipient as MultiAddress::Id
                _recipient,
                _amount.encode256()
            );
    }
// Solidity 0.7.6
// Decodes a SCALE encoded uint256 by converting bytes (bid endian) to little endian format
function decodeUint256(bytes memory data) public pure returns (uint256) {
        uint256 number;
        for (uint256 i = data.length; i > 0; i--) {
            number = number + uint256(uint8(data[i - 1])) * (2**(8 * (i - 1)));
        }
        return number;
    }
// Solidity 0.7.6
// Sources:
//   * https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity/50528
//   * https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel
function reverse256(uint256 input) internal pure returns (uint256 v) {
        v = input;

        // swap bytes
        v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
            ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);

        // swap 2-byte long pairs
        v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
            ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);

        // swap 4-byte long pairs
        v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) |
            ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);

        // swap 8-byte long pairs
        v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) |
            ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);

        // swap 16-byte long pairs
        v = (v >> 128) | (v << 128);
    }
// Solidity 0.8.9
// ========== Claiming ==========
function burnForPhysical(uint16[] calldata _burnTokenIds, uint16 editionId, uint16 editionTokenId, bool claimNFT) public whenNotPaused nonReentrant {
    require(editionId <= numBurnEditions, "Edition not found");
    require(_burnTokenIds.length > 0, "No tokens to burn");

    BurnEdition storage edition = burnEditions[editionId];

    require(edition.supportedToken == editionTokenId, "Token Id is not supported for edition");

    // Calculate quantity
    require(_burnTokenIds.length % edition.tokenCost == 0, "Quantity must be a multiple of token cost");
    uint16 _quantity = uint16(_burnTokenIds.length) / edition.tokenCost;

    // Can only claim if there is supply remaining
    numClaimsByTokenID[editionTokenId] += _quantity;
    require(numClaimsByTokenID[editionTokenId] <= maximumSupplyByTokenID[editionTokenId], "Not enough tokens remaining");

    // Check that tokens are owned by the caller and burn
    if(edition.contractType == ContractType.ERC721) {
      IERC721Burnable supportedContract = IERC721Burnable(edition.contractAddress);
      for (uint16 i=0; i < _burnTokenIds.length; i++) {
        supportedContract.burn(_burnTokenIds[i]);
      }
    } else if (edition.contractType == ContractType.ERC1155) {
      IERC1155Burnable supportedContract = IERC1155Burnable(edition.contractAddress);
      for (uint16 i=0; i < _burnTokenIds.length; i++) {
        supportedContract.burn(msg.sender, _burnTokenIds[i], 1);
      }
    }
    
    if(claimNFT) {
      _mint(msg.sender, editionTokenId, _quantity, "");
    }

    emit ClaimedPhysicalEdition(msg.sender, editionId, editionTokenId);
  }
// Solidity 0.4.25
/* setWinner function - set the winning contract */
function setWinner(uint256 _gameId) public onlyGameContractOrOwner {
		require(_gameId == gameContractObject.gameId());
		assert(gameContractObject.state() == GameContract.GameState.RandomReceived);
		assert(!isWinner);
		isWinner = true;
		address houseAddressOne = gameContractObject.getHouseAddressOne();
		address houseAddressTwo = gameContractObject.getHouseAddressTwo();
		address referralAddress = gameContractObject.getReferralAddress();
		if (totalBid == 0) {
			houseAddressOne.transfer((address(this).balance * 70)/100);
			houseAddressTwo.transfer(address(this).balance);
      settlementType = 0;
		} else if (totalBid == address(this).balance) {
		    settlementType = 1;
		} else {
			totalBalance = address(this).balance - totalBid;
			uint256 houseAddressShare = gameContractObject.getHouseAddressShare();
			houseAddressOne.transfer((totalBalance * houseAddressShare * 70) / 10000);/* 70 percent of house share goes to bucket one */
			houseAddressTwo.transfer((totalBalance * houseAddressShare * 30) / 10000);/* 30 percent of house share goes to bucket one */
			referralAmount = (totalBalance * gameContractObject.getReferralAddressShare())/100;	
			referralAddress.transfer(referralAmount);
			totalBalance = address(this).balance;
			settlementType = 2;
		}
		processed = 0;
		remaining = betters.length;
	}
// Solidity 0.7.4
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to a smart contract and receive approval
// - Owner's account must have sufficient balance to transfer
// - Smartcontract must accept the payment 
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferAndCall(address to, uint tokens, bytes memory data) public returns (bool success) {
        require (tokens <= balances[msg.sender] );
        balances[msg.sender] = safeSub(balances[msg.sender], tokens);
        balances[to] = safeAdd(balances[to], tokens);
        require (TransferAndCallFallBack(to).receiveTransfer(msg.sender, tokens, data));
        
        emit Transfer(msg.sender, to, tokens);
        return true;    
    }
// Solidity 0.7.4
// ----------------------------------------------------------------------------
// Buy EASY tokens for ETH by exchange rate
// ----------------------------------------------------------------------------
function buyTokens() public payable returns (bool success) {
        require (msg.value > 0, "ETH amount should be greater than zero");
        
        uint tokenAmount = _exchangeRate * msg.value; 
        balances[owner] = safeSub(balances[owner], tokenAmount);
        balances[msg.sender] = safeAdd(balances[msg.sender], tokenAmount);
        emit Transfer(owner, msg.sender, tokenAmount);
        return true;
    }
// Solidity 0.4.24
/// @dev Courtesy of https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol
/// This method allows the pre-defined recipient to call other smart contracts.
function externalCall(address destination, uint256 value, bytes data) public returns (bool) {
    require(msg.sender == recipient, "Sender must be the recipient.");
    uint256 dataLength = data.length;
    bool result;
    assembly {
      let x := mload(0x40)   // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
      let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
      result := call(
        sub(gas, 34710),     // 34710 is the value that solidity is currently emitting
                             // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
                             // callNewAccountGas (25000, in case the destination address does not exist and needs creating)
        destination,
        value,
        d,
        dataLength,          // Size of the input (in bytes) - this is what fixes the padding problem
        x,
        0                    // Output is ignored, therefore the output size is zero
      )
    }
    return result;
  }
// Solidity 0.6.12
// effects
// energy + metabolism
// OG1/2
// ghost aura effect
// indiv equip effect
// make sure this amt roughly on same magnitude with 1e18
function getVirtualAmt(uint256 tamagId) public view returns (uint256) {
        // cater to both tamag versions. Assume that any id is only either V1 OR V2, not both.
        uint256 trait = 0;
        bool isV2 = tamag.exists(tamagId);

        if (isV2){
            // it's a V2;
            trait = tamag.getTrait(tamagId);
        } else {
            trait = oldTamag.getTrait(tamagId);
        }

        // uint256 cheerfulness = getCheerfulness(trait);
        uint256 energy = getEnergy(trait);
        uint256 metabolism = getMetabolism(trait);
        // values obtained are out of 0-31 inclusive
        
        uint256 result = energy.add(metabolism).mul(1e18); // range of 0-64 1E18
        uint256 tempTamagId = isV2 ? tamagId : tamagId + 1; // see constructor for explanation
        if (og1.contains(tempTamagId)){
            result = result.mul(OG1_BONUS).div(100);
        }else if (og2.contains(tempTamagId)){
            result = result.mul(OG2_BONUS).div(100);
        }

        if (isV2){
            uint256 bonuses = getBonuses(tamagId);
            if (bonuses > 0){
                result = result.mul(bonuses.add(100)).div(100);
            }
        }

        return result;
    }
// Solidity 0.4.24
/**
 	 * @notice Create PixelCon `(_tokenId)`
 	 * @dev Throws if the token ID already exists
 	 * @param _to Address that will own the PixelCon
 	 * @param _tokenId ID of the PixelCon to be creates
 	 * @param _name PixelCon name (not required)
 	 * @return The index of the new PixelCon
 	 */
function create(address _to, uint256 _tokenId, bytes8 _name) public payable validAddress(_to) validId(_tokenId) returns(uint64)
	{
		TokenLookup storage lookupData = tokenLookup[_tokenId];
		require(pixelcons.length < uint256(2 ** 64) - 1, "Max number of PixelCons has been reached");
		require(lookupData.owner == address(0), "PixelCon already exists");

		//get created timestamp (zero as date indicates null)
		uint32 dateCreated = 0;
		if (now < uint256(2 ** 32)) dateCreated = uint32(now);

		//create PixelCon token and set owner
		uint64 index = uint64(pixelcons.length);
		lookupData.tokenIndex = index;
		pixelcons.length++;
		pixelconNames.length++;
		PixelCon storage pixelcon = pixelcons[index];
		pixelcon.tokenId = _tokenId;
		pixelcon.creator = msg.sender;
		pixelcon.dateCreated = dateCreated;
		pixelconNames[index] = _name;
		uint64[] storage createdList = createdTokens[msg.sender];
		uint createdListIndex = createdList.length;
		createdList.length++;
		createdList[createdListIndex] = index;
		addTokenTo(_to, _tokenId);

		emit Create(_tokenId, msg.sender, index, _to);
		emit Transfer(address(0), _to, _tokenId);
		return index;
	}
// Solidity 0.7.5
/**
 * @dev callback function that is called by BONK token.
 * @param _from who sent the tokens.
 * @param _tokens how many tokens were sent.
 * @param _data extra call data.
 * @return success.
 */
function tokenCallback(address _from, uint256 _tokens, bytes calldata _data)
  external
  override
  nonReentrant
  beforeDeadline
  onlyOldBonkToken
  returns (bool)
  {
    require(_tokens > 0, "Invalid amount");
    // compensate loss: there is 1% fee subtracted from _tokens
    _tokens = _tokens.mul(110).div(100);
    _migrate(_from, _tokens);
    return true;
  }
// Solidity 0.8.6
// Override with logic specific to this chain
function _bridgingLogic(uint256 token_type, address address_to_send_to, uint256 token_amount) internal override {
        // [Moonriver]
        if (token_type == 0){
            // L1 FRAX -> anyFRAX
            // Simple dump in / CREATE2
            // AnySwap Bridge
            TransferHelper.safeTransfer(address(FRAX), bridge_addresses[token_type], token_amount);
        }
        else if (token_type == 1) {
            // L1 FXS -> anyFXS
            // Simple dump in / CREATE2
            // AnySwap Bridge
            TransferHelper.safeTransfer(address(FXS), bridge_addresses[token_type], token_amount);
        }
        else {
            // L1 USDC -> anyUSDC
            // Simple dump in / CREATE2
            // AnySwap Bridge
            TransferHelper.safeTransfer(collateral_address, bridge_addresses[token_type], token_amount);
        }
    }
// Solidity 0.4.24
/**
 	 * @notice Rename PixelCon `(_tokenId)`
 	 * @dev Throws if the caller is not the owner and creator of the token
 	 * @param _tokenId ID of the PixelCon to rename
 	 * @param _name New name
 	 * @return The index of the PixelCon
 	 */
function rename(uint256 _tokenId, bytes8 _name) public validId(_tokenId) returns(uint64)
	{
		require(isCreatorAndOwner(msg.sender, _tokenId), "Sender is not the creator and owner");

		//update name
		TokenLookup storage lookupData = tokenLookup[_tokenId];
		pixelconNames[lookupData.tokenIndex] = _name;

		emit Rename(_tokenId, _name);
		return lookupData.tokenIndex;
	}
// Solidity 0.4.24
/**
 	 * @notice Get all details of PixelCon `(_tokenId)`
 	 * @dev Throws if PixelCon does not exist
 	 * @param _tokenId ID of the PixelCon to get details for
 	 * @return PixelCon details
 	 */
function getTokenData(uint256 _tokenId) public view validId(_tokenId)
	returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
	{
		TokenLookup storage lookupData = tokenLookup[_tokenId];
		require(lookupData.owner != address(0), "PixelCon does not exist");

		PixelCon storage pixelcon = pixelcons[lookupData.tokenIndex];
		return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
			pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
	}
// Solidity 0.4.24
/**
 	 * @notice Get all details of PixelCon #`(_tokenIndex)`
 	 * @dev Throws if PixelCon does not exist
 	 * @param _tokenIndex Index of the PixelCon to get details for
 	 * @return PixelCon details
 	 */
function getTokenDataByIndex(uint64 _tokenIndex) public view
	returns(uint256 _tknId, uint64 _tknIdx, uint64 _collectionIdx, address _owner, address _creator, bytes8 _name, uint32 _dateCreated)
	{
		require(_tokenIndex < totalSupply(), "PixelCon index is out of bounds");

		PixelCon storage pixelcon = pixelcons[_tokenIndex];
		TokenLookup storage lookupData = tokenLookup[pixelcon.tokenId];
		return (pixelcon.tokenId, lookupData.tokenIndex, pixelcon.collectionIndex, lookupData.owner,
			pixelcon.creator, pixelconNames[lookupData.tokenIndex], pixelcon.dateCreated);
	}
// Solidity 0.4.24
/**
 	 * @notice Create PixelCon collection
 	 * @dev Throws if the message sender is not the owner and creator of the given tokens
 	 * @param _tokenIndexes Token indexes to group together into a collection
 	 * @param _name Name of the collection
 	 * @return Index of the new collection
 	 */
function createCollection(uint64[] _tokenIndexes, bytes8 _name) public returns(uint64)
	{
		require(collectionNames.length < uint256(2 ** 64) - 1, "Max number of collections has been reached");
		require(_tokenIndexes.length > 1, "Collection must contain more than one PixelCon");

		//loop through given indexes to add to collection and check additional requirements
		uint64 collectionIndex = uint64(collectionNames.length);
		uint64[] storage collection = collectionTokens[collectionIndex];
		collection.length = _tokenIndexes.length;
		for (uint i = 0; i < _tokenIndexes.length; i++) {
			uint64 tokenIndex = _tokenIndexes[i];
			require(tokenIndex < totalSupply(), "PixelCon index is out of bounds");

			PixelCon storage pixelcon = pixelcons[tokenIndex];
			require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
			require(pixelcon.collectionIndex == uint64(0), "PixelCon is already in a collection");

			pixelcon.collectionIndex = collectionIndex;
			collection[i] = tokenIndex;
		}
		collectionNames.length++;
		collectionNames[collectionIndex] = _name;

		emit CreateCollection(msg.sender, collectionIndex);
		return collectionIndex;
	}
// Solidity 0.4.24
/**
 	 * @notice Rename collection #`(_collectionIndex)`
 	 * @dev Throws if the message sender is not the owner and creator of all collection tokens
 	 * @param _collectionIndex Index of the collection to rename
 	 * @param _name New name
 	 * @return Index of the collection
 	 */
function renameCollection(uint64 _collectionIndex, bytes8 _name) validIndex(_collectionIndex) public returns(uint64)
	{
		require(_collectionIndex < totalCollections(), "Collection does not exist");

		//loop through the collections token indexes and check additional requirements
		uint64[] storage collection = collectionTokens[_collectionIndex];
		require(collection.length > 0, "Collection has been cleared");
		for (uint i = 0; i < collection.length; i++) {
			PixelCon storage pixelcon = pixelcons[collection[i]];
			require(isCreatorAndOwner(msg.sender, pixelcon.tokenId), "Sender is not the creator and owner of the PixelCons");
		}

		//update
		collectionNames[_collectionIndex] = _name;

		emit RenameCollection(_collectionIndex, _name);
		return _collectionIndex;
	}