lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.5.4
/**
 	 * @dev Set a publicKey as the default for a Name
 	 * @param _id The ID of the Name
 	 * @param _defaultKey The defaultKey to be set
 	 * @param _signatureV The V part of the signature for this update
 	 * @param _signatureR The R part of the signature for this update
 	 * @param _signatureS The S part of the signature for this update
 	 */
function setDefaultKey(address _id, address _defaultKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) senderNameNotCompromised {
		require (this.isKeyExist(_id, _defaultKey));

		bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _defaultKey));
		require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);

		PublicKey storage _publicKey = publicKeys[_id];
		_publicKey.defaultKey = _defaultKey;

		uint256 _nonce = _nameFactory.incrementNonce(_id);
		require (_nonce > 0);
		emit SetDefaultKey(_id, _defaultKey, _nonce);
	}
// Solidity 0.5.4
/**
 	 * @dev Set a publicKey as the writer for a Name
 	 * @param _id The ID of the Name
 	 * @param _writerKey The writerKey to be set
 	 * @param _signatureV The V part of the signature for this update
 	 * @param _signatureR The R part of the signature for this update
 	 * @param _signatureS The S part of the signature for this update
 	 */
function setWriterKey(address _id, address _writerKey, uint8 _signatureV, bytes32 _signatureR, bytes32 _signatureS) public isName(_id) onlyAdvocate(_id) senderNameNotCompromised {
		bytes32 _hash = keccak256(abi.encodePacked(address(this), _id, _writerKey));
		require (ecrecover(_hash, _signatureV, _signatureR, _signatureS) == msg.sender);
		require (_setWriterKey(_id, _writerKey));
	}
// Solidity 0.5.4
/**
 	 * @dev Actual adding the publicKey to list for a Name
 	 * @param _id The ID of the Name
 	 * @param _key The publicKey to be added
 	 * @return true on success
 	 */
function _addKey(address _id, address _key) internal returns (bool) {
		require (!this.isKeyExist(_id, _key));

		keyToNameId[_key] = _id;

		PublicKey storage _publicKey = publicKeys[_id];
		_publicKey.keys.push(_key);

		uint256 _nonce = _nameFactory.incrementNonce(_id);
		require (_nonce > 0);

		emit AddKey(_id, _key, _nonce);
		return true;
	}
// Solidity 0.5.4
/**
 	 * @dev Actual setting the writerKey for a Name
 	 * @param _id The ID of the Name
 	 * @param _writerKey The writerKey to be set
 	 * @return true on success
 	 */
function _setWriterKey(address _id, address _writerKey) internal returns (bool) {
		require (this.isKeyExist(_id, _writerKey));

		PublicKey storage _publicKey = publicKeys[_id];
		_publicKey.writerKey = _writerKey;

		uint256 _nonce = _nameFactory.incrementNonce(_id);
		require (_nonce > 0);
		emit SetWriterKey(_id, _writerKey, _nonce);
		return true;
	}
// Solidity 0.7.5
/**
 *  @notice initializes bond parameters
 *  @param _controlVariable uint
 *  @param _vestingTerm uint
 *  @param _minimumPrice uint
 *  @param _maxPayout uint
 *  @param _fee uint
 *  @param _maxDebt uint
 *  @param _initialDebt uint
 */
function initializeBondTerms( 
        uint _controlVariable, 
        uint _vestingTerm,
        uint _minimumPrice,
        uint _maxPayout,
        uint _fee,
        uint _maxDebt,
        uint _initialDebt
    ) external onlyPolicy() {
        require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
        terms = Terms ({
            controlVariable: _controlVariable,
            vestingTerm: _vestingTerm,
            minimumPrice: _minimumPrice,
            maxPayout: _maxPayout,
            fee: _fee,
            maxDebt: _maxDebt
        });
        totalDebt = _initialDebt;
        lastDecay = block.number;
    }
// Solidity 0.7.5
/**
 *  @notice set parameters for new bonds
 *  @param _parameter PARAMETER
 *  @param _input uint
 */
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
        if ( _parameter == PARAMETER.VESTING ) { // 0
            require( _input >= 10000, "Vesting must be longer than 36 hours" );
            terms.vestingTerm = _input;
        } else if ( _parameter == PARAMETER.PAYOUT ) { // 1
            require( _input <= 1000, "Payout cannot be above 1 percent" );
            terms.maxPayout = _input;
        } else if ( _parameter == PARAMETER.FEE ) { // 2
            require( _input <= 10000, "DAO fee cannot exceed payout" );
            terms.fee = _input;
        } else if ( _parameter == PARAMETER.DEBT ) { // 3
            terms.maxDebt = _input;
        }
    }
// Solidity 0.7.5
/**
 *  @notice set control variable adjustment
 *  @param _addition bool
 *  @param _increment uint
 *  @param _target uint
 *  @param _buffer uint
 */
function setAdjustment ( 
        bool _addition,
        uint _increment, 
        uint _target,
        uint _buffer 
    ) external onlyPolicy() {
        require( _increment <= terms.controlVariable.mul( 25 ).div( 1000 ), "Increment too large" );

        adjustment = Adjust({
            add: _addition,
            rate: _increment,
            target: _target,
            buffer: _buffer,
            lastBlock: block.number
        });
    }
// Solidity 0.7.5
/**
 *  @notice set contract for auto stake
 *  @param _staking address
 *  @param _helper bool
 */
function setStaking( address _staking, bool _helper ) external onlyPolicy() {
        require( _staking != address(0) );
        if ( _helper ) {
            useHelper = true;
            stakingHelper = _staking;
        } else {
            useHelper = false;
            staking = _staking;
        }
    }
// Solidity 0.7.5
/** 
 *  @notice redeem bond for user
 *  @param _recipient address
 *  @param _stake bool
 *  @return uint
 */
function redeem( address _recipient, bool _stake ) external returns ( uint ) {        
        Bond memory info = bondInfo[ _recipient ];
        uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining)

        if ( percentVested >= 10000 ) { // if fully vested
            delete bondInfo[ _recipient ]; // delete user info
            emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data
            return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due

        } else { // if unfinished
            // calculate payout vested
            uint payout = info.payout.mul( percentVested ).div( 10000 );

            // store updated deposit info
            bondInfo[ _recipient ] = Bond({
                payout: info.payout.sub( payout ),
                vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ),
                lastBlock: block.number,
                pricePaid: info.pricePaid
            });

            emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout );
            return stakeOrSend( _recipient, _stake, payout );
        }
    }
// Solidity 0.7.5
/**
 *  @notice allow user to stake payout automatically
 *  @param _stake bool
 *  @param _amount uint
 *  @return uint
 */
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) {
        if ( !_stake ) { // if user does not want to stake
            IERC20( OHM ).transfer( _recipient, _amount ); // send payout
        } else { // if user wants to stake
            if ( useHelper ) { // use if staking warmup is 0
                IERC20( OHM ).approve( stakingHelper, _amount );
                IStakingHelper( stakingHelper ).stake( _amount, _recipient );
            } else {
                IERC20( OHM ).approve( staking, _amount );
                IStaking( staking ).stake( _amount, _recipient );
            }
        }
        return _amount;
    }
// Solidity 0.7.5
/**
 *  @notice makes incremental adjustment to control variable
 */
function adjust() internal {
        uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer );
        if( adjustment.rate != 0 && block.number >= blockCanAdjust ) {
            uint initial = terms.controlVariable;
            if ( adjustment.add ) {
                terms.controlVariable = terms.controlVariable.add( adjustment.rate );
                if ( terms.controlVariable >= adjustment.target ) {
                    adjustment.rate = 0;
                    terms.controlVariable = adjustment.target;
                }
            } else {
                terms.controlVariable = terms.controlVariable.sub( adjustment.rate );
                if ( terms.controlVariable <= adjustment.target ) {
                    adjustment.rate = 0;
                    terms.controlVariable = adjustment.target;
                }
            }
            adjustment.lastBlock = block.number;
            emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add );
        }
    }
// Solidity 0.7.5
/**
 *  @notice calculate current bond premium
 *  @return price_ uint
 */
function bondPrice() public view returns ( uint price_ ) {        
        price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
        if ( price_ < terms.minimumPrice ) {
            price_ = terms.minimumPrice;
        }
    }
// Solidity 0.7.5
/**
 *  @notice calculate current bond price and remove floor if above
 *  @return price_ uint
 */
function _bondPrice() internal returns ( uint price_ ) {
        price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 );
        if ( price_ < terms.minimumPrice ) {
            price_ = terms.minimumPrice;        
        } else if ( terms.minimumPrice != 0 ) {
            terms.minimumPrice = 0;
        }
    }
// Solidity 0.7.5
/**
 *  @notice converts bond price to DAI value
 *  @return price_ uint
 */
function bondPriceInUSD() public view returns ( uint price_ ) {
        if( isLiquidityBond ) {
            price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 );
        } else {
            price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 );
        }
    }
// Solidity 0.7.5
/**
 *  @notice debt ratio in same terms for reserve or liquidity bonds
 *  @return uint
 */
function standardizedDebtRatio() external view returns ( uint ) {
        if ( isLiquidityBond ) {
            return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 );
        } else {
            return debtRatio();
        }
    }
// Solidity 0.7.5
/**
 *  @notice amount to decay total debt by
 *  @return decay_ uint
 */
function debtDecay() public view returns ( uint decay_ ) {
        uint blocksSinceLast = block.number.sub( lastDecay );
        decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm );
        if ( decay_ > totalDebt ) {
            decay_ = totalDebt;
        }
    }
// Solidity 0.7.5
/**
 *  @notice calculate how far into vesting a depositor is
 *  @param _depositor address
 *  @return percentVested_ uint
 */
function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) {
        Bond memory bond = bondInfo[ _depositor ];
        uint blocksSinceLast = block.number.sub( bond.lastBlock );
        uint vesting = bond.vesting;

        if ( vesting > 0 ) {
            percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting );
        } else {
            percentVested_ = 0;
        }
    }
// Solidity 0.7.5
/**
 *  @notice calculate amount of OHM available for claim by depositor
 *  @param _depositor address
 *  @return pendingPayout_ uint
 */
function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) {
        uint percentVested = percentVestedFor( _depositor );
        uint payout = bondInfo[ _depositor ].payout;

        if ( percentVested >= 10000 ) {
            pendingPayout_ = payout;
        } else {
            pendingPayout_ = payout.mul( percentVested ).div( 10000 );
        }
    }
// Solidity 0.7.5
/**
 *  @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO
 *  @return bool
 */
function recoverLostToken( address _token ) external returns ( bool ) {
        require( _token != OHM );
        require( _token != principle );
        IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) );
        return true;
    }
// Solidity 0.5.16
/**
 	 * Anyone can call the function to deploy a new payment handler.
 	 * The new contract will be created, added to the list, and an event fired.
 	 */
function deployNewHandler() public {
		// Deploy the new contract
		PaymentHandler createdHandler = new PaymentHandler(this);

		// Add it to the list and the mapping
		handlerList.push(address(createdHandler));
		handlerMap[address(createdHandler)] = true;

		// Emit event to let watchers know that a new handler was created
		emit HandlerCreated(address(createdHandler));
	}
// Solidity 0.5.16
/**
 	 * This function is called by handlers when they receive ETH payments.
 	 */
function firePaymentReceivedEvent(address to, address from, uint256 amount) public {
		// Verify the call is coming from a handler
		require(handlerMap[msg.sender], "Only payment handlers are allowed to trigger payment events.");

		// Emit the event
		emit EthPaymentReceived(to, from, amount);
	}
// Solidity 0.5.16
/**
 	 * Allows a caller to sweep multiple handlers in one transaction
 	 */
function multiHandlerSweep(address[] memory handlers, IERC20 tokenContract) public {
		for (uint i = 0; i < handlers.length; i++) {

			// Whitelist calls to only handlers
			require(handlerMap[handlers[i]], "Only payment handlers are valid sweep targets.");

			// Trigger sweep
			PaymentHandler(address(uint160(handlers[i]))).sweepTokens(tokenContract);
		}
	}
// Solidity 0.4.24
/* Transfers based on an offline signed transfer instruction. */
function delegatedTransfer(address from, address to, uint amount, string narrative,
                                     uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
                                     bytes32 nonce, /* random nonce generated by client */
                                     /* ^^^^ end of signed data ^^^^ */
                                     bytes signature,
                                     uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
                                     )
    external {
        bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce));

        _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);

        _transfer(from, to, amount, narrative);
    }
// Solidity 0.4.24
/* transferAndNotify based on an  instruction signed offline  */
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
                                     uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */
                                     bytes32 nonce, /* random nonce generated by client */
                                     /* ^^^^ end of signed data ^^^^ */
                                     bytes signature,
                                     uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */
                                     )
    external {
        bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce));

        _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);

        _transfer(from, target, amount, "");
        target.transferNotification(from, amount, data);
    }
// Solidity 0.5.10
/**
 * @dev    Selling tokens back to the bonding curve for collateral.
 * @param  _numTokens: The number of tokens that you want to burn.
 */
function burn(uint256 _numTokens) external onlyActive() returns(bool) {
        require(
            balances[msg.sender] >= _numTokens,
            "Not enough tokens available"
        );

        uint256 reward = rewardForBurn(_numTokens);

        totalSupply_ = totalSupply_.sub(_numTokens);
        balances[msg.sender] = balances[msg.sender].sub(_numTokens);

        require(
            collateralToken_.transfer(
                msg.sender,
                reward
            ),
            "Tokens not sent"
        );

        emit Transfer(msg.sender, address(0), _numTokens);
        emit Burn(msg.sender, _numTokens, reward);
        return true;
    }
// Solidity 0.5.10
/**
 * @notice This function returns the amount of tokens one can receive for a
 *         specified amount of collateral token.
 * @param  _collateralTokenOffered : Amount of reserve token offered for
 *         purchase.
 * @return uint256 : The amount of tokens once can purchase with the
 *         specified collateral.
 */
function collateralToTokenBuying(
        uint256 _collateralTokenOffered
    )
        external
        view
        returns(uint256)
    {
        // Works out the amount of collateral for fee
        uint256 fee = _collateralTokenOffered.mul(feeRate_).div(100);
        // Removes the fee amount from the collateral offered
        uint256 amountLessFee = _collateralTokenOffered.sub(fee);
        // Works out the inverse curve of the pool with the fee removed amount
        return _inverseCurveIntegral(
                _curveIntegral(totalSupply_).add(amountLessFee)
            ).sub(totalSupply_);
    }
// Solidity 0.5.10
/**
 * @dev    Allows token holders to withdraw collateral in return for tokens
 * 		after the market has been finalised.
 * @param 	_amount: The amount of tokens they want to withdraw
 */
function withdraw(uint256 _amount) public returns(bool) {
        // Ensures withdraw can only be called in an inactive market
        require(!active_, "Market not finalised");
        // Ensures the sender has enough tokens
        require(_amount <= balances[msg.sender], "Insufficient funds");
        // Ensures there are no anomaly withdraws that might break calculations
        require(_amount > 0, "Cannot withdraw 0");

        // Removes amount from user balance
        balances[msg.sender] = balances[msg.sender].sub(_amount);
        // Gets the balance of the market (vault may send excess funding)
        uint256 balance = collateralToken_.balanceOf(address(this));

        // Performs a flat linear 100% collateralized sale
        uint256 collateralToTransfer = balance.mul(_amount).div(totalSupply_);
        // Removes token amount from the total supply
        totalSupply_ = totalSupply_.sub(_amount);

        // Ensures the sender is sent their collateral amount
        require(
            collateralToken_.transfer(msg.sender, collateralToTransfer),
            "Dai transfer failed"
        );

        emit Transfer(msg.sender, address(0), _amount);
        emit Burn(msg.sender, _amount, collateralToTransfer);

        return true;
    }
// Solidity 0.5.10
/**
 	  * @dev	Returns the required collateral amount for a volume of bonding
 	  *			curve tokens.
 * @notice The curve intergral code will reject any values that are too
 *         small or large, that could result in over/under flows.
 	  * @param	_numTokens: The number of tokens to calculate the price of
 * @return uint256 : The required collateral amount for a volume of bonding
 *         curve tokens.
 */
function priceToMint(uint256 _numTokens) public view returns(uint256) {
        // Gets the balance of the market
        uint256 balance = collateralToken_.balanceOf(address(this));
        // Performs the curve intergral with the relavant vaules
        uint256 collateral = _curveIntegral(
                totalSupply_.add(_numTokens)
            ).sub(balance);
        // Sets the base unit for decimal shift
        uint256 baseUnit = 100;
        // Adds the fee amount
        uint256 result = collateral.mul(100).div(baseUnit.sub(feeRate_));
        return result;
    }
// Solidity 0.5.10
/**
 	  * @dev	Returns the required collateral amount for a volume of bonding
 	  *			curve tokens
 	  * @param	_numTokens: The number of tokens to work out the collateral
 	  *			vaule of
 * @return uint256: The required collateral amount for a volume of bonding
 *         curve tokens
 */
function rewardForBurn(uint256 _numTokens) public view returns(uint256) {
        // Gets the curent balance of the market
        uint256 poolBalanceFetched = collateralToken_.balanceOf(address(this));
        // Returns the pool balance minus the curve intergral of the removed
        // tokens
        return poolBalanceFetched.sub(
            _curveIntegral(totalSupply_.sub(_numTokens))
        );
    }
// Solidity 0.5.10
/**
 * @notice Transfer ownership token from msg.sender to a specified address.
 * @param  _to : The address to transfer to.
 * @param  _value : The amount to be transferred.
 */
function transfer(address _to, uint256 _value) public returns (bool) {
        require(_value <= balances[msg.sender], "Insufficient funds");
        require(_to != address(0), "Target account invalid");

        balances[msg.sender] = balances[msg.sender].sub(_value);
        balances[_to] = balances[_to].add(_value);
        emit Transfer(msg.sender, _to, _value);
        return true;
    }
// Solidity 0.5.10
/**
 * @dev    Initialized the contract, sets up owners and gets the market
 *         address. This function exists because the Vault does not have
 *         an address until the constructor has finished running. The
 *         cumulative funding threshold is set here because of gas issues
 *         within the constructor.
 * @param _market: The market that will be sending this vault it's
 *         collateral.
 */
function initialize(
        address _market
    )
        external
        onlyWhitelistAdmin()
        returns(bool)
    {
        require(_market != address(0), "Contracts initialized");
        // Stores the market in storage 
        market_ = IMarket(_market); 
        // Removes the market factory contract as an admin
        super.renounceWhitelistAdmin();

        // Adding all previous rounds funding goals to the cumulative goal
        for(uint8 i = 0; i < totalRounds_; i++) {
            if(i == 0) {
                fundingPhases_[i].cumulativeFundingThreshold.add(
                    fundingPhases_[i].fundingThreshold
                );
            }
            fundingPhases_[i].cumulativeFundingThreshold.add(
                fundingPhases_[i-1].cumulativeFundingThreshold
            );
        }
        _active = true;

        return true;
    }
// Solidity 0.5.10
/**
 * @dev    This function sends the vaults funds to the market, and sets the
 *         outstanding withdraw to 0.
 * @notice If this function is called before the end of all phases, all
 *         unclaimed (outstanding) funding will be sent to the market to be
 *         redistributed.
 */
function terminateMarket()
        public
        isActive()
        onlyWhitelistAdmin()
    {
        uint256 remainingBalance = collateralToken_.balanceOf(address(this));
        // This ensures that if the creator has any outstanding funds, that
        // those funds do not get sent to the market.
        if(outstandingWithdraw_ > 0) {
            remainingBalance = remainingBalance.sub(outstandingWithdraw_);
        }
        // Transfers remaining balance to the market
        require(
            collateralToken_.transfer(address(market_), remainingBalance),
            "Transfering of funds failed"
        );
        // Finalizes market (stops buys/sells distributes collateral evenly)
        require(market_.finaliseMarket(), "Market termination error");
    }