lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.8.1
/**
 * withdraw() transfers out a single token after a pool is expired or empty 
 * id                    swap pool id
 * addr_i                withdraw token index
 * this function can only be called by the pool creator. after validation, it transfers the addr_i th token 
 * out to the pool creator address.
 **/
function withdraw (bytes32 id, uint256 addr_i) public {
        Pool storage pool = pool_by_id[id];
        require(msg.sender == pool.creator, "Only the pool creator can withdraw.");

        uint256 withdraw_balance = pool.exchanged_tokens[addr_i];
        require(withdraw_balance > 0, "None of this token left");
        uint256 expiration = unbox(pool.packed1, 228, 28) + base_time;
        uint256 remaining_tokens = unbox(pool.packed2, 0, 128);
        // only after expiration or the pool is empty
        require(expiration <= block.timestamp || remaining_tokens == 0, "Not expired yet");
        address token_address = pool.exchange_addrs[addr_i];

        // ERC20
        if (token_address != DEFAULT_ADDRESS)
            transfer_token(token_address, address(this), msg.sender, withdraw_balance);
        // ETH
        else
            payable(msg.sender).transfer(withdraw_balance);
        // clear the record
        pool.exchanged_tokens[addr_i] = 0;
        emit WithdrawSuccess(id, token_address, withdraw_balance);
    }
// Solidity 0.8.1
/**
 * _qualification the smart contract address to verify qualification      160
 * _hash          sha3-256(password)                                      40
 * _start         start time delta                                        28
 * _end           end time  delta                                         28
 * wrap1() inserts the above variables into a 32-word block
 **/
function wrap1 (address _qualification, bytes32 _hash, uint256 _start, uint256 _end) internal pure 
                    returns (uint256 packed1) {
        uint256 _packed1 = 0;
        _packed1 |= box(0, 160,  uint256(uint160(_qualification)));     // _qualification = 160 bits
        _packed1 |= box(160, 40, uint256(_hash) >> 216);                // hash = 40 bits (safe?)
        _packed1 |= box(200, 28, _start);                               // start_time = 28 bits 
        _packed1 |= box(228, 28, _end);                                 // expiration_time = 28 bits
        return _packed1;
    }
// Solidity 0.8.1
/**
 * _total_tokens   target remaining         128
 * _limit          single swap limit        128
 * wrap2() inserts the above variables into a 32-word block
 **/
function wrap2 (uint256 _total_tokens, uint256 _limit) internal pure returns (uint256 packed2) {
        uint256 _packed2 = 0;
        _packed2 |= box(0, 128, _total_tokens);             // total_tokens = 128 bits ~= 3.4e38
        _packed2 |= box(128, 128, _limit);                  // limit = 128 bits
        return _packed2;
    }
// Solidity 0.8.1
/**
 * position      position in a memory block
 * size          data size
 * data          data
 * box() inserts the data in a 256bit word with the given position and returns it
 * data is checked by validRange() to make sure it is not over size 
 **/
function box (uint16 position, uint16 size, uint256 data) internal pure returns (uint256 boxed) {
        require(validRange(size, data), "Value out of range BOX");
        assembly {
            // data << position
            boxed := shl(position, data)
        }
    }
// Solidity 0.8.1
/**
 * _box          32byte data to be modified
 * position      position in a memory block
 * size          data size
 * data          data to be inserted
 * rewriteBox() updates a 32byte word with a data at the given position with the specified size
 **/
function rewriteBox (uint256 _box, uint16 position, uint16 size, uint256 data) 
                        internal pure returns (uint256 boxed) {
        assembly {
            // mask = ~((1 << size - 1) << position)
            // _box = (mask & _box) | ()data << position)
            boxed := or( and(_box, not(shl(position, sub(shl(size, 1), 1)))), shl(position, data))
        }
    }
// Solidity 0.4.11
// ----------------------------
// withdraw expense funds to arbiter
// ----------------------------
function withdrawArbFunds() public
        {
                if (!validArb2(msg.sender)) {
                        StatEvent("invalid arbiter");
                } else {
                        arbiter xarb = arbiters[msg.sender];
                        if (xarb.arbHoldover == 0) { 
                                StatEvent("0 Balance");
                                return;
                        } else {
                                uint _amount = xarb.arbHoldover; 
                                xarb.arbHoldover = 0; 
                                if (!msg.sender.call.gas(acctCallGas).value(_amount)())
                                        throw;
                        }
                }
        }
// Solidity 0.8.12
// mint (Mint a token in the GuXeClub contract)
//  Anyone can call mint if they transfer the required ETH
//  Once the token is minted payments are transferred to the owner.
//  A RequestedGuXe event is emitted so that GuXeClub.com can
//   generate the image and update the URI. See setURI
function mint(uint256 parentId)
        public payable
    {
        require(sproutPaused != true, "Sprout is paused");        
        // Check if the parent GuXe exists         
        require(_exists(parentId), "Parent GuXe does not exists");

        uint256 currentSproutFee = getSproutFee(parentId);
        uint256 totalFee = artistFee.add(currentSproutFee);
        // Check if enough ETH was sent
        require(msg.value >= totalFee, "Did not provide enough ETH");

        tokenCount += 1;
        _safeMint(msg.sender, tokenCount);

        //want the request event to occur before transfer for ease workflow
        emit RequestedGuXe(tokenCount, parentId);

        //increase the sprout fee of the parent
        _incrementSproutFee(parentId);

        //transfer eth to parent owner account
        address parentOwner = ownerOf(parentId);

        //https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/
        (bool sent, bytes memory data) = parentOwner.call{value: currentSproutFee}("");
        require(sent, "Failed to send Ether");              
    }
// Solidity 0.8.12
// Set the URI to point a json file with metadata on the newly minted
//  Guxe Token. The file is stored on the IPFS distributed web and is immutable.
//  Once setURI is called for a token the URI can not be updated and 
//  the file on the IPFS system that the token points to can be verified as
//  unaltered as well. The json file is in a standard format used by opensea.io
//  It contains the image uri as well as information pertaining to the rareness
//  and limited additions of the art included in the image.
function setURI(uint256 _tokenId, string memory _tokenURI) 
        external onlyRole(URI_ROLE)
    {
        string memory defaultURI = string(abi.encodePacked(_baseURI(), _tokenId.toString()));
        string memory currentURI = super.tokenURI(_tokenId);
        require (compareStrings(defaultURI, currentURI), "URI has already been set.");

        //update the URI
        _setTokenURI(_tokenId, _tokenURI);
        string memory finalURI = super.tokenURI(_tokenId);


        //opensea will watch this
        emit PermanentURI(finalURI, _tokenId);
    }
// Solidity 0.5.10
/**
 * @notice Transfers vested tokens to beneficiary.
 */
function release() public {
        int8 unreleasedIdx = _releasableIdx(block.timestamp);

        require(unreleasedIdx >= 0, "TokenVesting: no tokens are due");

        uint256 unreleasedAmount = _amount.mul(_percent[uint(unreleasedIdx)]).div(100);

        _token.safeTransfer(_beneficiary, unreleasedAmount);

        _percent[uint(unreleasedIdx)] = 0;
        _released = _released.add(unreleasedAmount);

        emit TokensReleased(address(_token), unreleasedAmount);
    }
// Solidity 0.5.10
/**
 * @dev Calculates the index that has already vested but hasn't been released yet.
 */
function _releasableIdx(uint256 ts) private view returns (int8) {
        for (uint8 i = 0; i < _schedule.length; i++) {
            if (ts > _schedule[i] && _percent[i] > 0) {
                return int8(i);
            }
        }

        return -1;
    }
// Solidity 0.5.0
/* @notice This function was invoked when user want to swap their collections with skully
 	 * @param skullyId the id of skully that user want to swap
 	 * @param exchangeTokenId the id of their collections
 	 * @param typeERC the number of erc721 in the list of contract that allow to exchange with 
 	 * return none - just emit a result to the network
 	*/
function swap(uint256 skullyId, uint256 exchangeTokenId, uint64 typeERC) public whenNotPaused {
        ERC721(listERC721[typeERC]).transferFrom(msg.sender, address(this), exchangeTokenId);
        // cancel sale auction
        auctionContract.cancelAuction(skullyId);
        
        // set flag
        itemContract.increaseSkullyExp(skullyId, plusFlags);
        
        skullyContract.transferFrom(address(this), msg.sender, skullyId);
        
        emit Swapped(skullyId, exchangeTokenId, typeERC, block.timestamp);
    }
// Solidity 0.8.1
/**
 * Get randomness from Chainlink VRF to propose winners.
 */
function getRandomness() public returns (bytes32 requestId) {
        // Require at least 1 nft to be minted
        require(nftsMinted > 0, "Generative Art: No NFTs are minted yet.");
        //Require caller to be contract owner or all 10K NFTs need to be minted
        require(msg.sender == owner() || nftsMinted == nftMintLimit , "Generative Art: Only Owner can collectWinner. All 10k NFTs need to be minted for others to collectWinner.");
        // Require Winners to be not yet selected
        require(!winnersSelected, "Generative Art: Winners already selected");
        // Require chainlinkAvailable >= Chainlink VRF fee
        require(IERC20(LINKTokenAddress).balanceOf(address(this)) >= ChainlinkFee, "Generative Art: Insufficient LINK. Please deposit LINK.");
        // Call for random number
        return requestRandomness(ChainlinkKeyHash, ChainlinkFee);
    }
// Solidity 0.8.1
/**
 * Disburses prize money to winners
 */
function disburseWinners() external {
        // Require at least 1 nft to be minted
        require(nftsMinted > 0, "Generative Art: No NFTs are minted.");
        // Require caller to be contract owner or all 10K NFTs need to be minted
        require(msg.sender == owner() || nftsMinted == nftMintLimit , "Generative Art: Only Owner can disburseWinner. All 10k NFTs need to be minted for others to disburseWinner.");
        // Require that all winners be selected first before disbursing
        require(winnersSelected, "Generative Art: Winners needs to be selected first");
        //Get account balance
        uint256 accountBalance = address(this).balance;   
        // While winners disbursed is less than total winners
        while (winnersDisbursed < maxWinners) {
            // Get winner
            address winner = ownerOf(winnerIDs[winnersDisbursed]);
            // Transfer Prize Money to winner
            payable(winner).transfer((accountBalance*prizeMoneyPercent[winnersDisbursed])/100);
            // Increment winnersDisbursed
            winnersDisbursed++;
        }
    }
// Solidity 0.5.4
/**
 	 * @dev Check if `_tokenAddress` is a valid ERC20 Token address
 	 * @param _tokenAddress The ERC20 Token address to check
 	 */
function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) {
		if (_tokenAddress == address(0)) {
			return false;
		}
		TokenERC20 _erc20 = TokenERC20(_tokenAddress);
		return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
	}
// Solidity 0.5.4
/**
 	 * @dev Checks if the calling contract address is The AO
 	 *		OR
 	 *		If The AO is set to a Name/TAO, then check if calling address is the Advocate
 	 * @param _sender The address to check
 	 * @param _theAO The AO address
 	 * @param _nameTAOPositionAddress The address of NameTAOPosition
 	 * @return true if yes, false otherwise
 	 */
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
		return (_sender == _theAO ||
			(
				(isTAO(_theAO) || isName(_theAO)) &&
				_nameTAOPositionAddress != address(0) &&
				INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
			)
		);
	}
// Solidity 0.5.4
/**
 	 * @dev deploy a TAO
 	 * @param _name The name of the TAO
 	 * @param _originId The Name ID the creates the TAO
 	 * @param _datHash The datHash of this TAO
 	 * @param _database The database for this TAO
 	 * @param _keyValue The key/value pair to be checked on the database
 	 * @param _contentId The contentId related to this TAO
 	 * @param _nameTAOVaultAddress The address of NameTAOVault
 	 */
function deployTAO(string memory _name,
		address _originId,
		string memory _datHash,
		string memory _database,
		string memory _keyValue,
		bytes32 _contentId,
		address _nameTAOVaultAddress
		) public returns (TAO _tao) {
		_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
	}
// Solidity 0.5.4
/**
 	 * @dev Calculate the new weighted multiplier when adding `_additionalPrimordialAmount` at `_additionalWeightedMultiplier` to the current `_currentPrimordialBalance` at `_currentWeightedMultiplier`
 	 * @param _currentWeightedMultiplier Account's current weighted multiplier
 	 * @param _currentPrimordialBalance Account's current primordial ion balance
 	 * @param _additionalWeightedMultiplier The weighted multiplier to be added
 	 * @param _additionalPrimordialAmount The primordial ion amount to be added
 	 * @return the new primordial weighted multiplier
 	 */
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
		if (_currentWeightedMultiplier > 0) {
			uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
			uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount);
			return _totalWeightedIons.div(_totalIons);
		} else {
			return _additionalWeightedMultiplier;
		}
	}
// Solidity 0.5.4
/**
 	 * @dev Calculate the bonus amount of network ion on a given lot
 	 *		AO Bonus Amount = B% x P
 	 *
 	 * @param _purchaseAmount The amount of primordial ion intended to be purchased
 	 * @param _totalPrimordialMintable Total Primordial ion intable
 	 * @param _totalPrimordialMinted Total Primordial ion minted so far
 	 * @param _startingMultiplier The starting Network ion bonus multiplier
 	 * @param _endingMultiplier The ending Network ion bonus multiplier
 	 * @return The bonus percentage
 	 */
function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
		uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
		/**
		 * Since bonusPercentage is in _PERCENTAGE_DIVISOR format, need to divide it with _PERCENTAGE DIVISOR
		 * when calculating the network ion bonus amount
		 */
		uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
		return networkBonus;
	}
// Solidity 0.5.4
/**
 	 *
 	 * @dev Whitelisted address remove `_value` TAOCurrency from the system irreversibly on behalf of `_from`.
 	 *
 	 * @param _from the address of the sender
 	 * @param _value the amount of money to burn
 	 */
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist isNameOrTAO(_from) returns (bool success) {
		require(balanceOf[_from] >= _value);                // Check if the targeted balance is enough
		balanceOf[_from] = balanceOf[_from].sub(_value);    // Subtract from the targeted balance
		totalSupply = totalSupply.sub(_value);              // Update totalSupply
		emit Burn(_from, _value);
		return true;
	}
// Solidity 0.5.4
/**
 	 * @dev Send `_value` TAOCurrency from `_from` to `_to`
 	 * @param _from The address of sender
 	 * @param _to The address of the recipient
 	 * @param _value The amount to send
 	 */
function _transfer(address _from, address _to, uint256 _value) internal {
		require (_to != address(0));							// Prevent transfer to 0x0 address. Use burn() instead
		require (balanceOf[_from] >= _value);					// Check if the sender has enough
		require (balanceOf[_to].add(_value) >= balanceOf[_to]); // Check for overflows
		uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
		balanceOf[_from] = balanceOf[_from].sub(_value);        // Subtract from the sender
		balanceOf[_to] = balanceOf[_to].add(_value);            // Add the same to the recipient
		emit Transfer(_from, _to, _value);
		assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
	}
// Solidity 0.5.4
/**
 	 * @dev The AO adds denomination and the contract address associated with it
 	 * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
 	 * @param denominationAddress The address of the denomination TAOCurrency
 	 * @return true on success
 	 */
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
		require (denominationName.length > 0);
		require (denominationName[0] != 0);
		require (denominationAddress != address(0));
		require (denominationIndex[denominationName] == 0);
		totalDenominations++;
		// Make sure the new denomination is higher than the previous
		if (totalDenominations > 1) {
			TAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations - 1].denominationAddress);
			TAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);
			require (_newDenominationTAOCurrency.powerOfTen() > _lastDenominationTAOCurrency.powerOfTen());
		}
		denominations[totalDenominations].name = denominationName;
		denominations[totalDenominations].denominationAddress = denominationAddress;
		denominationIndex[denominationName] = totalDenominations;
		return true;
	}
// Solidity 0.5.4
/**
 	 * @dev The AO updates denomination address or activates/deactivates the denomination
 	 * @param denominationName The name of the denomination, i.e ao, kilo, mega, etc.
 	 * @param denominationAddress The address of the denomination TAOCurrency
 	 * @return true on success
 	 */
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO isValidDenomination(denominationName) returns (bool) {
		require (denominationAddress != address(0));
		uint256 _denominationNameIndex = denominationIndex[denominationName];
		TAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);
		if (_denominationNameIndex > 1) {
			TAOCurrency _prevDenominationTAOCurrency = TAOCurrency(denominations[_denominationNameIndex - 1].denominationAddress);
			require (_newDenominationTAOCurrency.powerOfTen() > _prevDenominationTAOCurrency.powerOfTen());
		}
		if (_denominationNameIndex < totalDenominations) {
			TAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations].denominationAddress);
			require (_newDenominationTAOCurrency.powerOfTen() < _lastDenominationTAOCurrency.powerOfTen());
		}
		denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
		return true;
	}
// Solidity 0.5.4
/**
 	 * @dev Get denomination info by index
 	 * @param index The index to be queried
 	 * @return the denomination short name
 	 * @return the denomination address
 	 * @return the denomination public name
 	 * @return the denomination symbol
 	 * @return the denomination num of decimals
 	 * @return the denomination multiplier (power of ten)
 	 */
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string memory, string memory, uint8, uint256) {
		require (index > 0 && index <= totalDenominations);
		require (denominations[index].denominationAddress != address(0));
		TAOCurrency _tc = TAOCurrency(denominations[index].denominationAddress);
		return (
			denominations[index].name,
			denominations[index].denominationAddress,
			_tc.name(),
			_tc.symbol(),
			_tc.decimals(),
			_tc.powerOfTen()
		);
	}
// Solidity 0.5.4
/**
 	 * @dev convert TAOCurrency from `denominationName` denomination to base denomination,
 	 *		in this case it's similar to web3.toWei() functionality
 	 *
 	 * Example:
 	 * 9.1 Kilo should be entered as 9 integerAmount and 100 fractionAmount
 	 * 9.02 Kilo should be entered as 9 integerAmount and 20 fractionAmount
 	 * 9.001 Kilo should be entered as 9 integerAmount and 1 fractionAmount
 	 *
 	 * @param integerAmount uint256 of the integer amount to be converted
 	 * @param fractionAmount uint256 of the frational amount to be converted
 	 * @param denominationName bytes8 name of the TAOCurrency denomination
 	 * @return uint256 converted amount in base denomination from target denomination
 	 */
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) external view returns (uint256) {
		uint256 _fractionAmount = fractionAmount;
		if (this.isDenominationExist(denominationName) && (integerAmount > 0 || _fractionAmount > 0)) {
			Denomination memory _denomination = denominations[denominationIndex[denominationName]];
			TAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);
			uint8 fractionNumDigits = AOLibrary.numDigits(_fractionAmount);
			require (fractionNumDigits <= _denominationTAOCurrency.decimals());
			uint256 baseInteger = integerAmount.mul(10 ** _denominationTAOCurrency.powerOfTen());
			if (_denominationTAOCurrency.decimals() == 0) {
				_fractionAmount = 0;
			}
			return baseInteger.add(_fractionAmount);
		} else {
			return 0;
		}
	}
// Solidity 0.5.4
/**
 	 * @dev convert TAOCurrency from base denomination to `denominationName` denomination,
 	 *		in this case it's similar to web3.fromWei() functionality
 	 * @param integerAmount uint256 of the base amount to be converted
 	 * @param denominationName bytes8 name of the target TAOCurrency denomination
 	 * @return uint256 of the converted integer amount in target denomination
 	 * @return uint256 of the converted fraction amount in target denomination
 	 */
function fromBase(uint256 integerAmount, bytes8 denominationName) public view returns (uint256, uint256) {
		if (this.isDenominationExist(denominationName)) {
			Denomination memory _denomination = denominations[denominationIndex[denominationName]];
			TAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);
			uint256 denominationInteger = integerAmount.div(10 ** _denominationTAOCurrency.powerOfTen());
			uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationTAOCurrency.powerOfTen()));
			return (denominationInteger, denominationFraction);
		} else {
			return (0, 0);
		}
	}