lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.6.7
/**
 @dev given a token supply, connector balance, weight and a sell amount (in the main token),
 calculates the return for a given conversion (in the connector token)
 
 Formula:
 Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000)))
 
 @param _supply              token total supply
 @param _connectorBalance    total connector
 @param _connectorWeight     constant connector Weight, represented in ppm, 1-1000000
 @param _sellAmount          sell amount, in the token itself
 
 @return sale return amount
 */
function calculateRedeemReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) {
        // validate input
        require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply);

        // special case for 0 sell amount
        if (_sellAmount == 0)
            return 0;

        // special case for selling the entire supply
        if (_sellAmount == _supply)
            return _connectorBalance;

        // special case if the weight = 100%
        if (_connectorWeight == MAX_WEIGHT)
            return safeMul(_connectorBalance, _sellAmount) / _supply;

        uint256 result;
        uint8 precision;
        uint256 baseD = _supply - _sellAmount;
        (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight);
        uint256 temp1 = safeMul(_connectorBalance, result);
        uint256 temp2 = _connectorBalance << precision;
        return (temp1 - temp2) / result;
    }
// Solidity 0.6.7
// support _baseN < _baseD
function power2(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) public view returns (uint256, uint8) {
        if(_baseN >= _baseD)
            return power(_baseN, _baseD, _expN, _expD);
        uint256 lnBaseTimesExp = ln(_baseD, _baseN) * _expN / _expD;
        uint8 precision = findPositionInMaxExpArray(lnBaseTimesExp);
        if(precision < MIN_PRECISION)
            return (0, 0);
        uint256 base = fixedExp(lnBaseTimesExp >> (MAX_PRECISION - precision), precision);
        base = (uint256(1) << (MIN_PRECISION + MAX_PRECISION)) / base;
        precision = MIN_PRECISION + MAX_PRECISION - precision;
        return (base, precision);
    }
// Solidity 0.6.7
/**
 Return floor(ln(numerator / denominator) * 2 ^ MAX_PRECISION), where:
 - The numerator   is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
 - The denominator is a value between 1 and 2 ^ (256 - MAX_PRECISION) - 1
 - The output      is a value between 0 and floor(ln(2 ^ (256 - MAX_PRECISION) - 1) * 2 ^ MAX_PRECISION)
 This functions assumes that the numerator is larger than or equal to the denominator, because the output would be negative otherwise.
 */
function ln(uint256 _numerator, uint256 _denominator) public pure returns (uint256) {
        assert(_numerator <= MAX_NUM);

        uint256 res = 0;
        uint256 x = _numerator * FIXED_1 / _denominator;

        // If x >= 2, then we compute the integer part of log2(x), which is larger than 0.
        if (x >= FIXED_2) {
            uint8 count = floorLog2(x / FIXED_1);
            x >>= count; // now x < 2
            res = count * FIXED_1;
        }

        // If x > 1, then we compute the fraction part of log2(x), which is larger than 0.
        if (x > FIXED_1) {
            for (uint8 i = MAX_PRECISION; i > 0; --i) {
                x = (x * x) / FIXED_1; // now 1 < x < 4
                if (x >= FIXED_2) {
                    x >>= 1; // now 1 < x < 2
                    res += ONE << (i - 1);
                }
            }
        }

        return res * LN2_NUMERATOR / LN2_DENOMINATOR;
    }
// Solidity 0.4.4
//An arbitrary versioning scheme.
function HumanStandardToken(
        uint256 _initialAmount,
        string _tokenName,
        uint8 _decimalUnits,
        string _tokenSymbol
        ) {
        balances[msg.sender] = _initialAmount; // Give the creator all initial tokens
        totalSupply = _initialAmount;          // Update total supply
        name = _tokenName;                     // Set the name for display purposes
        decimals = _decimalUnits;              // Amount of decimals for display purposes
        symbol = _tokenSymbol;                 // Set the symbol for display purposes
    }
// Solidity 0.4.4
/// @notice `createTokens()` will create tokens if the campaign has not been
/// sealed.
/// @dev `createTokens()` is called by the campaign contract when
/// someone sends ether to that contract or calls `doPayment()`
/// @param beneficiary The address receiving the tokens
/// @param amount The amount of tokens the address is receiving
/// @return True if tokens are created
function createTokens(address beneficiary, uint amount
    ) onlyController returns (bool success) {
        if (sealed()) throw;
        balances[beneficiary] += amount;  // Create tokens for the beneficiary
        totalSupply += amount;            // Update total supply
        Transfer(0, beneficiary, amount); // Create an Event for the creation
        return true;
    }
// Solidity 0.4.4
/// @notice 'Campaign()' initiates the Campaign by setting its funding
/// parameters and creating the deploying the token contract
/// @dev There are several checks to make sure the parameters are acceptable
/// @param _startFundingTime The UNIX time that the Campaign will be able to
/// start receiving funds
/// @param _endFundingTime The UNIX time that the Campaign will stop being able
/// to receive funds
/// @param _maximumFunding In wei, the Maximum amount that the Campaign can
/// receive (currently the max is set at 10,000 ETH for the beta)
/// @param _vaultContract The address that will store the donated funds
function Campaign(
        uint _startFundingTime,
        uint _endFundingTime,
        uint _maximumFunding,
        address _vaultContract
    ) {
        if ((_endFundingTime < now) ||                // Cannot start in the past
            (_endFundingTime <= _startFundingTime) ||
            (_maximumFunding > 10000 ether) ||        // The Beta is limited
            (_vaultContract == 0))                    // To prevent burning ETH
            {
            throw;
            }
        startFundingTime = _startFundingTime;
        endFundingTime = _endFundingTime;
        maximumFunding = _maximumFunding;
        tokenContract = new CampaignToken (); // Deploys the Token Contract
        vaultContract = _vaultContract;
    }
// Solidity 0.4.4
/// @dev `doPayment()` is an internal function that sends the ether that this
/// contract receives to the `vaultContract` and creates campaignTokens in the
/// address of the `_owner` assuming the Campaign is still accepting funds
/// @param _owner The address that will hold the newly created CampaignTokens
function doPayment(address _owner) internal {

// First we check that the Campaign is allowed to receive this donation
        if ((now<startFundingTime) ||
            (now>endFundingTime) ||
            (tokenContract.tokenController() == 0) ||           // Extra check
            (msg.value == 0) ||
            (totalCollected + msg.value > maximumFunding))
        {
            throw;
        }

//Track how much the Campaign has collected
        totalCollected += msg.value;

//Send the ether to the vaultContract
        if (!vaultContract.send(msg.value)) {
            throw;
        }

// Creates an equal amount of CampaignTokens as ether sent. The new CampaignTokens
// are created in the `_owner` address
        if (!tokenContract.createTokens(_owner, msg.value)) {
            throw;
        }

        return;
    }
// Solidity 0.4.25
// @dev Removes an address from an admin for a game
// @notice Can only be called by an admin of the game.
// @notice Can't remove your own account's admin privileges.
// @param _game - the gameId of the game
// @param _account - the address of the user to remove admin privileges.
function removeAdminAccount(uint _game, address _account)
    external
    onlyGameAdmin(_game)
  {
    require(_account != msg.sender);
    require(gameAdmins[_game][_account]);
    
    address[] storage opsAddresses = adminAddressesByGameId[_game];
    uint startingLength = opsAddresses.length;
    // Yes, "i < startingLength" is right. 0 - 1 == uint.maxvalue, not -1.
    for (uint i = opsAddresses.length - 1; i < startingLength; i--) {
      if (opsAddresses[i] == _account) {
        uint newLength = opsAddresses.length.sub(1);
        opsAddresses[i] = opsAddresses[newLength];
        delete opsAddresses[newLength];
        opsAddresses.length = newLength;
      }
    }

    uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account];
    startingLength = gamesByAdmin.length;
    for (i = gamesByAdmin.length - 1; i < startingLength; i--) {
      if (gamesByAdmin[i] == _game) {
        newLength = gamesByAdmin.length.sub(1);
        gamesByAdmin[i] = gamesByAdmin[newLength];
        delete gamesByAdmin[newLength];
        gamesByAdmin.length = newLength;
      }
    }

    gameAdmins[_game][_account] = false;
    emit AdminPrivilegesChanged(_game, _account, false);
  }
// Solidity 0.4.25
// @dev Internal function to add an address as an admin for a game
// @param _game - the gameId of the game
// @param _account - the address of the user
function _addAdminAccount(uint _game, address _account)
    internal
  {
    address[] storage opsAddresses = adminAddressesByGameId[_game];
    require(opsAddresses.length < 256, "a game can only have 256 admins");
    for (uint i = opsAddresses.length; i < opsAddresses.length; i--) {
      require(opsAddresses[i] != _account);
    }

    uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account];
    require(gamesByAdmin.length < 256, "you can only own 256 games");
    for (i = gamesByAdmin.length; i < gamesByAdmin.length; i--) {
      require(gamesByAdmin[i] != _game, "you can't become an operator twice");
    }
    gamesByAdmin.push(_game);

    opsAddresses.push(_account);
    gameAdmins[_game][_account] = true;
    emit AdminPrivilegesChanged(_game, _account, true);
  }
// Solidity 0.4.25
// @dev Create a new game by setting its data. 
//   Created games are initially owned and managed by the game's creator
// @notice - there's a maximum of 2^32 games (4.29 billion games)
// @param _json - a json encoded string containing the game's name, uri, logo, description, etc
// @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser's account
// @param _metadata - game-specific metadata, in bytes32 format. 
function createGame(string _json, uint _tradeLockSeconds, bytes32[] _metadata) 
    external
  returns(uint _game) {
    // Create the game
    _game = games.length;
    require(_game < games[0], "too many games created");
    games.push(_game);

    // Log the game as created
    emit GameCreated(_game, msg.sender, _json, _metadata);

    // Add the creator as the first game admin
    _addAdminAccount(_game, msg.sender);

    // Store the game's metadata
    updateGameMetadata(_game, _json, _tradeLockSeconds, _metadata);
  }
// Solidity 0.4.25
// @dev Get all game data for one given game
// @param _game - the # of the game
// @returns game - the game ID of the requested game
// @returns json - the json data of the game
// @returns tradeLockSeconds - the number of card sets
// @returns balance - the Nova Token balance 
// @returns metadata - a bytes32 array of metadata used by the game
function getGameData(uint _game)
    external
    view
  returns(uint game,
    string json,
    uint tradeLockSeconds,
    uint256 balance,
    bytes32[] metadata) 
  {
    GameData storage data = gameData[_game];
    game = _game;
    json = data.json;
    tradeLockSeconds = data.tradeLockSeconds;
    balance = stakingContract.balanceOf(address(_game));
    metadata = data.metadata;
  }
// Solidity 0.4.25
// @dev Update the json, trade lock, and metadata for a single game
// @param _game - the # of the game
// @param _json - a json encoded string containing the game's name, uri, logo, description, etc
// @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser's account
// @param _metadata - game-specific metadata, in bytes32 format. 
function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata)
    public
    onlyGameAdmin(_game)
  {
    gameData[_game].tradeLockSeconds = _tradeLockSeconds;
    gameData[_game].json = _json;

    bytes32[] storage data = gameData[_game].metadata;
    if (_metadata.length > data.length) { data.length = _metadata.length; }
    for (uint k = 0; k < _metadata.length; k++) { data[k] = _metadata[k]; }
    for (k; k < data.length; k++) { delete data[k]; }
    if (_metadata.length < data.length) { data.length = _metadata.length; }

    emit GameMetadataUpdated(_game, _json, _tradeLockSeconds, _metadata);
  }
// Solidity 0.8.4
// Claim egg and tokens
function claimEgg(uint256 stakingSetKey) external {
        // checks
        require(keyToStakingSet[stakingSetKey].owner == msg.sender, "Unauthorized");
        require(keyToStakingSet[stakingSetKey].eggClaimed == false, "Already claimed");
        require(block.timestamp > keyToStakingSet[stakingSetKey].timestamp + WAITING_TIMES_EGG_CLAIMING[keyToStakingSet[stakingSetKey].tokenIds.length-1], "Too early");

        // mint egg and mark as claimed
        Whelps breed7NFT = Whelps(_7thBreedContract);
        uint256 eggTokenId = breed7NFT.mint(msg.sender, keyToStakingSet[stakingSetKey].tokenId);
        keyToStakingSet[stakingSetKey].eggClaimed = true;

        // emit event for further reference
        emit ClaimEgg(msg.sender, stakingSetKey, eggTokenId);
    }
// Solidity 0.5.17
/**
 @notice This function is used to invest in given balancer pool through ETH/ERC20 Tokens
 @param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
 @param _ToBalancerPoolAddress The address of balancer pool to zapin
 @param _amount The amount of ERC to invest
 @param _minPoolTokens for slippage
 @return success or failure
 */
function ZapIn(
        address _FromTokenContractAddress,
        address _ToBalancerPoolAddress,
        uint256 _amount,
        uint256 _minPoolTokens
    )
        public
        payable
        nonReentrant
        stopInEmergency
        returns (uint256 tokensBought)
    {
        require(
            BalancerFactory.isBPool(_ToBalancerPoolAddress),
            "Invalid Balancer Pool"
        );

        emit zap(
            address(this),
            msg.sender,
            _FromTokenContractAddress,
            _amount,
            now
        );

        if (_FromTokenContractAddress == address(0)) {
            require(msg.value > 0, "ERR: No ETH sent");

            //transfer eth to goodwill
            uint256 goodwillPortion = _transferGoodwill(address(0), msg.value);

            address _IntermediateToken = _getBestDeal(
                _ToBalancerPoolAddress,
                msg.value,
                _FromTokenContractAddress
            );

            tokensBought = _performZapIn(
                msg.sender,
                _FromTokenContractAddress,
                _ToBalancerPoolAddress,
                msg.value.sub(goodwillPortion),
                _IntermediateToken,
                _minPoolTokens
            );

            return tokensBought;
        }

        require(_amount > 0, "ERR: No ERC sent");
        require(msg.value == 0, "ERR: ETH sent with tokens");

        //transfer tokens to contract
        IERC20(_FromTokenContractAddress).safeTransferFrom(
            msg.sender,
            address(this),
            _amount
        );

        //send tokens to goodwill
        uint256 goodwillPortion = _transferGoodwill(
            _FromTokenContractAddress,
            _amount
        );

        address _IntermediateToken = _getBestDeal(
            _ToBalancerPoolAddress,
            _amount,
            _FromTokenContractAddress
        );

        tokensBought = _performZapIn(
            msg.sender,
            _FromTokenContractAddress,
            _ToBalancerPoolAddress,
            _amount.sub(goodwillPortion),
            _IntermediateToken,
            _minPoolTokens
        );
    }
// Solidity 0.5.17
/**
 @notice This function internally called by ZapIn() and EasyZapIn()
 @param _toWhomToIssue The user address who want to invest
 @param _FromTokenContractAddress The token used for investment (address(0x00) if ether)
 @param _ToBalancerPoolAddress The address of balancer pool to zapin
 @param _amount The amount of ETH/ERC to invest
 @param _IntermediateToken The token for intermediate conversion before zapin
 @param _minPoolTokens for slippage
 @return The quantity of Balancer Pool tokens returned
 */
function _performZapIn(
        address _toWhomToIssue,
        address _FromTokenContractAddress,
        address _ToBalancerPoolAddress,
        uint256 _amount,
        address _IntermediateToken,
        uint256 _minPoolTokens
    ) internal returns (uint256 tokensBought) {
        // check if isBound()
        bool isBound = IBPool(_ToBalancerPoolAddress).isBound(
            _FromTokenContractAddress
        );

        uint256 balancerTokens;

        if (isBound) {
            balancerTokens = _enter2Balancer(
                _ToBalancerPoolAddress,
                _FromTokenContractAddress,
                _amount,
                _minPoolTokens
            );
        } else {
            // swap tokens or eth
            uint256 tokenBought;
            if (_FromTokenContractAddress == address(0)) {
                tokenBought = _eth2Token(_amount, _IntermediateToken);
            } else {
                tokenBought = _token2Token(
                    _FromTokenContractAddress,
                    _IntermediateToken,
                    _amount
                );
            }

            //get BPT
            balancerTokens = _enter2Balancer(
                _ToBalancerPoolAddress,
                _IntermediateToken,
                tokenBought,
                _minPoolTokens
            );
        }

        //transfer tokens to user
        IERC20(_ToBalancerPoolAddress).safeTransfer(
            _toWhomToIssue,
            balancerTokens
        );
        return balancerTokens;
    }
// Solidity 0.5.17
/**
 @notice This function is used to zapin to balancer pool
 @param _ToBalancerPoolAddress The address of balancer pool to zap in
 @param _FromTokenContractAddress The token used to zap in
 @param tokens2Trade The amount of tokens to invest
 @return The quantity of Balancer Pool tokens returned
 */
function _enter2Balancer(
        address _ToBalancerPoolAddress,
        address _FromTokenContractAddress,
        uint256 tokens2Trade,
        uint256 _minPoolTokens
    ) internal returns (uint256 poolTokensOut) {
        require(
            IBPool(_ToBalancerPoolAddress).isBound(_FromTokenContractAddress),
            "Token not bound"
        );

        uint256 allowance = IERC20(_FromTokenContractAddress).allowance(
            address(this),
            _ToBalancerPoolAddress
        );

        if (allowance < tokens2Trade) {
            IERC20(_FromTokenContractAddress).safeApprove(
                _ToBalancerPoolAddress,
                uint256(-1)
            );
        }

        poolTokensOut = IBPool(_ToBalancerPoolAddress).joinswapExternAmountIn(
            _FromTokenContractAddress,
            tokens2Trade,
            _minPoolTokens
        );

        require(poolTokensOut > 0, "Error in entering balancer pool");
    }
// Solidity 0.5.17
/**
 @notice Function gives the expected amount of pool tokens on investing
 @param _ToBalancerPoolAddress Address of balancer pool to zapin
 @param _IncomingERC The amount of ERC to invest
 @param _FromToken Address of token to zap in with
 @return Amount of BPT token
 */
function getToken2BPT(
        address _ToBalancerPoolAddress,
        uint256 _IncomingERC,
        address _FromToken
    ) internal view returns (uint256 tokensReturned) {
        uint256 totalSupply = IBPool(_ToBalancerPoolAddress).totalSupply();
        uint256 swapFee = IBPool(_ToBalancerPoolAddress).getSwapFee();
        uint256 totalWeight = IBPool(_ToBalancerPoolAddress)
            .getTotalDenormalizedWeight();
        uint256 balance = IBPool(_ToBalancerPoolAddress).getBalance(_FromToken);
        uint256 denorm = IBPool(_ToBalancerPoolAddress).getDenormalizedWeight(
            _FromToken
        );

        tokensReturned = IBPool(_ToBalancerPoolAddress)
            .calcPoolOutGivenSingleIn(
            balance,
            denorm,
            totalSupply,
            totalWeight,
            _IncomingERC,
            swapFee
        );
    }
// Solidity 0.5.17
/**
 @notice This function is used to buy tokens from eth
 @param _tokenContractAddress Token address which we want to buy
 @return The quantity of token bought
 */
function _eth2Token(uint256 _ethAmt, address _tokenContractAddress)
        internal
        returns (uint256 tokenBought)
    {
        if (_tokenContractAddress == wethTokenAddress) {
            IWETH(wethTokenAddress).deposit.value(_ethAmt)();
            return _ethAmt;
        }

        address[] memory path = new address[](2);
        path[0] = wethTokenAddress;
        path[1] = _tokenContractAddress;
        tokenBought = uniswapRouter.swapExactETHForTokens.value(_ethAmt)(
            1,
            path,
            address(this),
            deadline
        )[path.length - 1];
    }
// Solidity 0.5.17
/**
 * @notice Initialize the new money market
 * @param comptroller_ The address of the Comptroller
 * @param interestRateModel_ The address of the interest rate model
 * @param name_ ERC-20 name of this token
 * @param symbol_ ERC-20 symbol of this token
 */
function initialize(ComptrollerInterface comptroller_,
                        InterestRateModel interestRateModel_,
                        string memory name_,
                        string memory symbol_,
                        uint256 reserveFactorMantissa_,
                        uint256 adminFeeMantissa_) public {
        // CToken initialize does the bulk of the work
        uint256 initialExchangeRateMantissa_ = 0.2e18;
        uint8 decimals_ = 18;
        super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, reserveFactorMantissa_, adminFeeMantissa_);
    }
// Solidity 0.8.2
/**
 * @notice createIDO
 */
function createIDO(
        uint256 saleTarget,
        address fundToken,
        uint256 fundTarget,
        uint256 startTime,
        uint256 endTime,
        uint256 claimTime,
        uint256 minFundAmount,
        uint256 fcfsAmount,
        string memory meta
    ) external isOperatorOrOwner returns (address) {
        IDOSec ido = new IDOSec(this, saleTarget, fundToken, fundTarget);

        ido.setBaseData(startTime, endTime, claimTime, minFundAmount, fcfsAmount, meta);

        ido.transferOwnership(msg.sender);

        IDOs.push(address(ido));

        emit NewIDOCreated(address(ido), msg.sender);

        return address(ido);
    }
// Solidity 0.4.15
/**
 * Accept ownership request, works only if called by new owner
 */
function acceptOwnership() {
        // Avoid multiple events triggering in case of several calls from owner
        if (msg.sender == newOwner && owner != newOwner) {
            OwnershipTransferred(owner, newOwner);
            owner = newOwner;
        }
    }