lohoz/Smart-Contract-MultiTask-Dataset huggingface dataset:
// Solidity 0.4.21
/**
 @dev returns the expected return for converting a specific amount of _fromToken to _toToken
 
 @param _fromToken  ERC20 token to convert from
 @param _toToken    ERC20 token to convert to
 @param _amount     amount to convert, in fromToken
 
 @return expected conversion return amount
 */
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
        require(_fromToken != _toToken); // validate input

        // conversion between the token and one of its connectors
        if (_toToken == token)
            return getPurchaseReturn(_fromToken, _amount);
        else if (_fromToken == token)
            return getSaleReturn(_toToken, _amount);

        // conversion between 2 connectors
        return getCrossConnectorReturn(_fromToken, _toToken, _amount);
    }
// Solidity 0.4.21
/**
 @dev returns the expected return for buying the token for a connector token
 
 @param _connectorToken  connector token contract address
 @param _depositAmount   amount to deposit (in the connector token)
 
 @return expected purchase return amount
 */
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
        public
        view
        active
        validConnector(_connectorToken)
        returns (uint256)
    {
        Connector storage connector = connectors[_connectorToken];
        require(connector.isPurchaseEnabled); // validate input

        uint256 tokenSupply = token.totalSupply();
        uint256 connectorBalance = getConnectorBalance(_connectorToken);
        IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
        uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);

        // return the amount minus the conversion fee
        return getFinalAmount(amount, 1);
    }
// Solidity 0.4.21
/**
 @dev returns the expected return for selling the token for one of its connector tokens
 
 @param _connectorToken  connector token contract address
 @param _sellAmount      amount to sell (in the smart token)
 
 @return expected sale return amount
 */
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount)
        public
        view
        active
        validConnector(_connectorToken)
        returns (uint256)
    {
        Connector storage connector = connectors[_connectorToken];
        uint256 tokenSupply = token.totalSupply();
        uint256 connectorBalance = getConnectorBalance(_connectorToken);
        IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
        uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount);

        // return the amount minus the conversion fee
        return getFinalAmount(amount, 1);
    }
// Solidity 0.4.21
/**
 @dev returns the expected return for selling one of the connector tokens for another connector token
 
 @param _fromConnectorToken  contract address of the connector token to convert from
 @param _toConnectorToken    contract address of the connector token to convert to
 @param _sellAmount          amount to sell (in the from connector token)
 
 @return expected sale return amount (in the to connector token)
 */
function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount)
        public
        view
        active
        validConnector(_fromConnectorToken)
        validConnector(_toConnectorToken)
        returns (uint256)
    {
        Connector storage fromConnector = connectors[_fromConnectorToken];
        Connector storage toConnector = connectors[_toConnectorToken];
        require(toConnector.isPurchaseEnabled); // validate input

        uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken);
        uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken);

        IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
        uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount);

        // return the amount minus the conversion fee
        // the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token)
        return getFinalAmount(amount, 2);
    }
// Solidity 0.4.21
/**
 @dev buys the token by depositing one of its connector tokens
 
 @param _connectorToken  connector token contract address
 @param _depositAmount   amount to deposit (in the connector token)
 @param _minReturn       if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
 
 @return buy return amount
 */
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
        uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
        // ensure the trade gives something in return and meets the minimum requested amount
        require(amount != 0 && amount >= _minReturn);

        // update virtual balance if relevant
        Connector storage connector = connectors[_connectorToken];
        if (connector.isVirtualBalanceEnabled)
            connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);

        // transfer funds from the caller in the connector token
        assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
        // issue new funds to the caller in the smart token
        token.issue(msg.sender, amount);

        // calculate conversion fee and dispatch the conversion event
        uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1));
        dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount);

        // dispatch price data update for the smart token/connector
        emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);
        return amount;
    }
// Solidity 0.4.21
/**
 @dev helper, dispatches the Conversion event
 
 @param _fromToken       ERC20 token to convert from
 @param _toToken         ERC20 token to convert to
 @param _amount          amount purchased/sold (in the source token)
 @param _returnAmount    amount returned (in the target token)
 */
function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
        // fee amount is converted to 255 bits -
        // negative amount means the fee is taken from the source token, positive amount means its taken from the target token
        // currently the fee is always taken from the target token
        // since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
        assert(_feeAmount <= 2 ** 255);
        emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));
    }
// Solidity 0.5.17
/**
 * @dev get '_account' stakes by page
 */
function getStakes(address _account, uint _index, uint _offset) external view returns (StakeSet.Item[] memory items) {
        uint totalSize = userOrders(_account);
        require(0 < totalSize && totalSize > _index, "getStakes: 0 < totalSize && totalSize > _index");
        uint offset = _offset;
        if (totalSize < _index + offset) {
            offset = totalSize - _index;
        }

        items = new StakeSet.Item[](offset);
        for (uint i = 0; i < offset; i++) {
            items[i] = _stakeOf[_account].at(_index + i);
        }
    }
// Solidity 0.5.17
// todo: get token usdt price from swap
function getUSDTPrice(address _token) public view returns (uint) {

        if (payToken == _token) {return 1 ether;}
        (bool success, bytes memory returnData) = lpAddress[_token].staticcall(abi.encodeWithSignature("getReserves()"));
        if (success) {
            (uint112 reserve0, uint112 reserve1, ) = abi.decode(returnData, (uint112, uint112, uint32));
            uint DECIMALS = 10**18;
            if(_token==aToken){
                DECIMALS = 10**6;
                //return uint(reserve1).mul(DECIMALS).div(uint(reserve0));
            }
            //return uint(reserve0).mul(DECIMALS).div(uint(reserve1));
            return uint(reserve1).mul(DECIMALS).div(uint(reserve0));
        }

        return 0;
    }
// Solidity 0.5.17
// https://uniswap.org/docs/v2/smart-contract-integration/getting-pair-addresses/
function _pairFor(address _factory, address tokenA, address tokenB) internal pure returns (address pair) {

    // sort tokens
    (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);

    require(token0 != token1, "TWAP: identical addresses");
    require(token0 != address(0), "TWAP: zero address");

    pair = address(uint(keccak256(abi.encodePacked(
        hex'ff',
        _factory,
        keccak256(abi.encodePacked(token0, token1)),
        hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
      ))));
  }
// Solidity 0.5.17
/* update */
function update(address[] calldata pairs) external {

    for (uint i = 0; i < pairs.length; i++) {

      // note: not reusing canUpdate() because we need the bucket variable
      address pair = pairs[i];
      uint index = timestampToIndex(block.timestamp);
      Bucket storage bucket = buckets[pair][index];

      if (block.timestamp - bucket.timestamp < periodSize) {
        continue;
      }

      (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);
      bucket.timestamp = block.timestamp;
      bucket.price0Cumulative = price0Cumulative;
      bucket.price1Cumulative = price1Cumulative;

      emit Updated(pair, block.timestamp, price0Cumulative, price1Cumulative);
    }
  }
// Solidity 0.5.17
/* consult */
function _getCumulativePrices(
    address tokenIn,
    address tokenOut
  ) internal view returns (uint priceCumulativeStart, uint priceCumulativeEnd, uint timeElapsed) {

    uint currentIndex = timestampToIndex(block.timestamp);
    uint firstBucketIndex = (currentIndex + 1) % periodsPerWindow;

    address pair = _pairFor(factory, tokenIn, tokenOut);
    Bucket storage firstBucket = buckets[pair][firstBucketIndex];

    timeElapsed = block.timestamp - firstBucket.timestamp;
    require(timeElapsed <= windowSize, "TWAP: missing historical reading");
    require(timeElapsed >= windowSize - periodSize * 2, "TWAP: unexpected time elapsed");

    (uint price0Cumulative, uint price1Cumulative,) = UniswapV2OracleLibrary.currentCumulativePrices(pair);

    if (tokenIn < tokenOut) {
      return (firstBucket.price0Cumulative, price0Cumulative, timeElapsed);
    }

    return (firstBucket.price1Cumulative, price1Cumulative, timeElapsed);
  }
// Solidity 0.5.17
/**
 *  @dev Returns the amount out corresponding to the amount in for a given token using the
 *  @dev   moving average over the time range [now - [windowSize, windowSize - periodSize * 2], now]
 *  @dev   update must have been called for the bucket corresponding to timestamp `now - windowSize`
 */
function consult(address tokenIn, uint amountIn, address tokenOut) external view returns (uint amountOut) {

    uint pastPriceCumulative;
    uint currentPriceCumulative;
    uint timeElapsed;

    (pastPriceCumulative, currentPriceCumulative, timeElapsed) = _getCumulativePrices(tokenIn, tokenOut);

    return _computeAmountOut(
      pastPriceCumulative,
      currentPriceCumulative,
      timeElapsed,
      amountIn
    );
  }
// Solidity 0.5.11
/** @dev Calls createDispute function of the specified arbitrator to create a dispute.
 *  @param _arbitrator The arbitrator of prospective dispute.
 *  @param _arbitratorExtraData Extra data for the arbitrator of prospective dispute.
 *  @param _metaevidenceURI Link to metaevidence of prospective dispute.
 */
function createDispute(Arbitrator _arbitrator, bytes calldata _arbitratorExtraData, string calldata _metaevidenceURI) external payable {
        uint arbitrationCost = _arbitrator.arbitrationCost(_arbitratorExtraData);
        require(msg.value >= arbitrationCost, "Insufficient message value.");
        uint disputeID = _arbitrator.createDispute.value(arbitrationCost)(NUMBER_OF_CHOICES, _arbitratorExtraData);

        uint localDisputeID = disputes.length++;
        DisputeStruct storage dispute = disputes[localDisputeID];
        dispute.arbitrator = _arbitrator;
        dispute.arbitratorExtraData = _arbitratorExtraData;
        dispute.disputeIDOnArbitratorSide = disputeID;
        dispute.rounds.length++;

        arbitratorExternalIDtoLocalID[address(_arbitrator)][disputeID] = localDisputeID;

        emit MetaEvidence(localDisputeID, _metaevidenceURI);
        emit Dispute(_arbitrator, disputeID, localDisputeID, localDisputeID);

        msg.sender.send(msg.value-arbitrationCost);
    }
// Solidity 0.5.11
/** @dev Manages contributions and calls appeal function of the specified arbitrator to appeal a dispute. This function lets appeals be crowdfunded.
 *  @param _localDisputeID Index of the dispute in disputes array.
 *  @param _party The side to which the caller wants to contribute.
 */
function appeal(uint _localDisputeID, Party _party) external payable {
        require(_party != Party.RefuseToArbitrate, "You can't fund an appeal in favor of refusing to arbitrate.");
        uint8 side = uint8(_party);
        DisputeStruct storage dispute = disputes[_localDisputeID];

        (uint appealPeriodStart, uint appealPeriodEnd) = dispute.arbitrator.appealPeriod(dispute.disputeIDOnArbitratorSide);
        require(now >= appealPeriodStart && now < appealPeriodEnd, "Funding must be made within the appeal period.");

        Round storage round = dispute.rounds[dispute.rounds.length-1];

        require(!round.hasPaid[side], "Appeal fee has already been paid");
        round.hasPaid[side] = true; // Temporarily assume the contribution covers the missing amount to block re-entrancy.

        uint appealCost = dispute.arbitrator.appealCost(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);

        uint contribution;

        if(round.paidFees[side] + msg.value >= appealCost){
          contribution = appealCost - round.paidFees[side];
        }
        else{
            contribution = msg.value;
            round.hasPaid[side] = false; // Rollback the temporary assumption above.
        }
        msg.sender.send(msg.value - contribution);
        round.contributions[msg.sender][side] += contribution;
        round.paidFees[side] += contribution;
        round.totalAppealFeesCollected += contribution;

        if(round.hasPaid[requester] && round.hasPaid[respondent]){
            dispute.arbitrator.appeal.value(appealCost)(dispute.disputeIDOnArbitratorSide, dispute.arbitratorExtraData);
            dispute.rounds.length++;
            round.totalAppealFeesCollected = round.totalAppealFeesCollected.subCap(appealCost);
        }
    }
// Solidity 0.5.11
/** @dev To be called by the arbitrator of the dispute, to declare winning side.
 *  @param _externalDisputeID ID of the dispute in arbitrator contract.
 *  @param _ruling The side to which the caller wants to contribute.
 */
function rule(uint _externalDisputeID, uint _ruling) external {
        uint _localDisputeID = arbitratorExternalIDtoLocalID[msg.sender][_externalDisputeID];
        DisputeStruct storage dispute = disputes[_localDisputeID];
        require(msg.sender == address(dispute.arbitrator), "Unauthorized call.");
        require(_ruling <= NUMBER_OF_CHOICES, "Invalid ruling.");
        require(dispute.isRuled == false, "Is ruled already.");

        dispute.isRuled = true;
        dispute.judgment = Party(_ruling);

        Round storage round = dispute.rounds[dispute.rounds.length-1];

        uint resultRuling = _ruling;
        if (round.hasPaid[requester] == true) // If one side paid its fees, the ruling is in its favor. Note that if the other side had also paid, an appeal would have been created.
            resultRuling = 1;
        else if (round.hasPaid[respondent] == true)
            resultRuling = 2;

        emit Ruling(Arbitrator(msg.sender), dispute.disputeIDOnArbitratorSide, resultRuling);
    }
// Solidity 0.4.23
/* Initializes the contract */
function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
        balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.
        totalSupply           = initialSupply; // Update total supply.
        name                  = tokenName;     // Set the name for display purposes.
        symbol                = tokenSymbol;   // Set the symbol for display purposes.
        decimals              = decimalUnits;  // Amount of decimals for display purposes.
    }
// Solidity 0.4.23
/// @notice Send `_value` tokens to `_to` in behalf of `_from`.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
        require(_value <= allowance[_from][msg.sender]); // Check allowance.
        allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
        _transfer(_from, _to, _value); // Makes the transfer.
        return true;
    }
// Solidity 0.4.23
/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend.
function approve(address _spender, uint256 _value) public returns (bool success) {
        allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.
        return true;
    }
// Solidity 0.4.23
/* Overrides basic transfer function due to comision value */
function transfer(address _to, uint256 _value) public {
    	// This function requires a comision value of 0.4% of the market value.
        uint market_value = _value * sellPrice;
        uint comision = market_value * 4 / 1000;
        // The token smart-contract pays comision, else the transfer is not possible.
        require(this.balance >= comision);
        comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
        _transfer(msg.sender, _to, _value);
    }
// Solidity 0.4.23
/* Internal, updates the profit value */
function _updateProfit(uint256 _increment, bool add) internal{
        if (add){
            // Increase the profit value
            profit = profit + _increment;
        }else{
            // Decrease the profit value
            if(_increment > profit){ profit = 0; }
            else{ profit = profit - _increment; }
        }
    }
// Solidity 0.4.23
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.
/// @param target Address to be frozen.
/// @param freeze Either to freeze target or not.
function freezeAccount(address target, bool freeze) onlyOwner public {
        frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.
        FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.
    }
// Solidity 0.4.23
/// @notice Deposits Ether to the contract
function deposit() payable public returns(bool success) {
        require((this.balance + msg.value) > this.balance); // Checks for overflows.
        //Contract has already received the Ether when this function is executed.
        _updateSolvency(this.balance);   // Updates the solvency value of the contract.
        _updateProfit(msg.value, false); // Decrease profit value.
        // Decrease because deposits will be done mostly by the owner.
        // Possible donations won't count as profit for the company, but in favor of the investors.
        LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received.
        return true;
    }
// Solidity 0.4.23
/// @notice The owner withdraws Ether from the contract.
/// @param amountInWeis Amount of ETH in WEI which will be withdrawed.
function withdraw(uint amountInWeis) onlyOwner public {
        LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
        _updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
        _updateProfit(amountInWeis, true);                // Increase the profit value.
        owner.transfer(amountInWeis); // Sends the Ether to owner address.
    }
// Solidity 0.4.18
// For pushing pre-ICO records
function push(address buyer, uint256 amount) public onlyOwner { //b753a98c
        require(balances[wallet] >= amount);
        require(now < startDate);
        require(buyer != wallet);

        preICO_address[ buyer ] = true;

        // Transfer
        balances[wallet] = balances[wallet].sub(amount);
        balances[buyer] = balances[buyer].add(amount);
        PreICOTokenPushed(buyer, amount);
    }
// Solidity 0.8.6
/// @dev Mature the fyToken by recording the chi.
function _mature() 
        private
        returns (uint256 _chiAtMaturity)
    {
        (_chiAtMaturity,) = oracle.get(underlyingId, CHI, 0);   // The value returned is an accumulator, it doesn't need an input amount
        chiAtMaturity = _chiAtMaturity;
        emit SeriesMatured(_chiAtMaturity);
    }
// Solidity 0.8.6
/// @dev Retrieve the chi accrual since maturity, maturing if necessary.
/// Note: Call only after checking we are past maturity
function _accrual()
        private
        returns (uint256 accrual_)
    {
        if (chiAtMaturity == CHI_NOT_SET) {  // After maturity, but chi not yet recorded. Let's record it, and accrual is then 1.
            _mature();
        } else {
            (uint256 chi,) = oracle.get(underlyingId, CHI, 0);   // The value returned is an accumulator, it doesn't need an input amount
            accrual_ = chi.wdiv(chiAtMaturity);
        }
        accrual_ = accrual_ >= 1e18 ? accrual_ : 1e18;     // The accrual can't be below 1 (with 18 decimals)
    }
// Solidity 0.8.6
/// @dev Burn fyToken after maturity for an amount that increases according to `chi`
/// If `amount` is 0, the contract will redeem instead the fyToken balance of this contract. Useful for batches.
function redeem(address to, uint256 amount)
        external override
        afterMaturity
        returns (uint256 redeemed)
    {
        uint256 amount_ = (amount == 0) ? _balanceOf[address(this)] : amount;
        _burn(msg.sender, amount_);
        redeemed = amount_.wmul(_accrual());
        join.exit(to, redeemed.u128());
        
        emit Redeemed(msg.sender, to, amount_, redeemed);
    }
// Solidity 0.8.6
/// @dev Burn fyTokens. 
/// Any tokens locked in this contract will be burned first and subtracted from the amount to burn from the user's wallet.
/// This feature allows someone to transfer fyToken to this contract to enable a `burn`, potentially saving the cost of `approve` or `permit`.
function _burn(address from, uint256 amount)
        internal override
        returns (bool)
    {
        // First use any tokens locked in this contract
        uint256 available = _balanceOf[address(this)];
        if (available >= amount) {
            return super._burn(address(this), amount);
        } else {
            if (available > 0 ) super._burn(address(this), available);
            unchecked { _decreaseAllowance(from, amount - available); }
            unchecked { return super._burn(from, amount - available); }
        }
    }