NEW

Chainlink Data Streams have officially launched on mainnet. Sign up for early access.

Back

Using the StreamsLookup error handler

The Chainlink Automation StreamsLookup error handler provides insight into potential errors or edge cases in StreamsLookup upkeeps. The table below outlines a range of error codes and the behavior associated with the codes. Use the checkErrorHandler function to specify how you want to respond to the error codes. checkErrorHandler is simulated offchain and determines what action for Automation to take onchain in performUpkeep.

Error handler

When Automation detects an event, it runs the checkLog function, which includes a StreamsLookup revert custom error. The StreamsLookup revert enables your upkeep to fetch a report from Data Streams. If reports are fetched successfully, the checkCallback function is evaluated offchain. Otherwise, the checkErrorHandler function is evaluated offchain to determine what Automation should do next. Both of these functions have the same output types (bool upkeepNeeded, bytes memory performData), which Automation uses to run performUpkeep onchain. The example code also shows each function outlined in the diagram below:

Error handler flow diagram

If the Automation network fails to get the requested reports, an error code is sent to the checkErrorHandler function in your contract. If your contract doesn't have the checkErrorHandler function, nothing will happen. If your contract has the checkErrorHandler function, it is evaluated offchain to determine what to do next. For example, you could intercept or ignore certain errors and decide not to run performUpkeep in those cases, in order to save time and gas. For other errors, you can execute an alternative path within performUpkeep, and the upkeep runs the custom logic you define in your performUpkeep function to handle those errors.

  1. Add the checkErrorHandler function in your contract to specify how you want to handle error codes. For example, you could decide to ignore any codes related to bad requests or incorrect input, without running performUpkeep onchain:

    function checkErrorHandler(
      uint errorCode,
      bytes calldata extraData
    ) external returns (bool upkeepNeeded, bytes memory performData) {
      // Add custom logic to handle errors offchain here
      bool _upkeepNeeded = true;
      bool success = false;
      bool isError = true;
      if (errorCode == 808400) {
        // Handle bad request error code offchain
        _upkeepNeeded = false;
      } else {
        // logic to handle other errors
      }
      return (_upkeepNeeded, abi.encode(isError, abi.encode(errorCode, extraData, success)));
    }
  2. Define custom logic for the alternative path within performUpkeep, to handle any error codes you did not intercept offchain in checkErrorHandler:

    // function will be performed on-chain
    function performUpkeep(bytes calldata performData) external {
      // Decode incoming performData
      (bool isError, bytes payload) = abi.decode(performData)
    
      // Unpacking the errorCode from checkErrorHandler
      if (isError){
        (uint errorCode, bytes memory extraData, bool reportSuccess) = abi.decode(
        payload,
        (uint, bytes, bool)
    
        // Define custom logic here to handle error codes onchain
      );
      } else {
        // Otherwise unpacking info from checkCallback
        (bytes[] memory signedReports, bytes memory extraData, bool reportSuccess) = abi.decode(
          payload,
          (bytes[], bytes, bool)
        );
        if (reportSuccess) {
        bytes memory report = signedReports[0];
    
        (, bytes memory reportData) = abi.decode(report, (bytes32[3], bytes));
    
        // Logic to verify and decode report
        } else {
          // Logic in case reports were not pulled successfully
        }
      }
    }

Testing checkErrorHandler

checkErrorHandler is simulated offchain. When upkeepNeeded returns true, Automation runs performUpkeep onchain using the performData from checkErrorHandler. If the checkErrorHandler function itself reverts, performUpkeep does not run.

If you need to force errors in StreamsLookup while testing, you can try the following methods:

  • Specifying an incorrect feedID to force error code 808400 (ErrCodeStreamsBadRequest)
  • Specifying a future timestamp to force error code 808206 (where partial content is received) for both single feedID and bulk feedID requests
  • Specifying old timestamps for reports not available anymore yields either error code 808504 (no response) or 808600 (bad response), depending on which service calls the timeout request

If your StreamsLookup revert function is defined incorrectly in your smart contracts, the nodes will not be able to decode it.

Error codes

Error codeRetriesPossible cause of error
No errorN/ANo error
ErrCodeStreamsBadRequest: 808400NoUser requested 0 feeds
User error, incorrect parameter input
Issue with encoding http url (bad characters)
ErrCodeStreamsUnauthorized: 808401NoKey access issue or incorrect feedID
808206Log trigger - after retries; Conditional immediatelyRequested m reports but only received n (partial)
8085XX (e.g 808500)Log trigger - after retries; Conditional immediatelyNo response
ErrCodeStreamsBadResponse: 808600NoError in reading body of returned response, but service is up
ErrCodeStreamsTimeout: 808601NoNo valid report is received for 10 seconds
ErrCodeStreamsUnknownError: 808700NoUnknown

Example code

This example code includes the revert StreamsLookup, checkCallback, checkErrorHandler and performUpkeep functions. The full code example is available here.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import {StreamsLookupCompatibleInterface} from "@chainlink/contracts/src/v0.8/automation/interfaces/StreamsLookupCompatibleInterface.sol";
import {ILogAutomation, Log} from "@chainlink/contracts/src/v0.8/automation/interfaces/ILogAutomation.sol";
import {IRewardManager} from "@chainlink/contracts/src/v0.8/llo-feeds/interfaces/IRewardManager.sol";
import {IVerifierFeeManager} from "@chainlink/contracts/src/v0.8/llo-feeds/interfaces/IVerifierFeeManager.sol";
import {IERC20} from "@chainlink/contracts/src/v0.8/vendor/openzeppelin-solidity/v4.8.0/contracts/interfaces/IERC20.sol";
import {Common} from "@chainlink/contracts/src/v0.8/libraries/Common.sol";

/**
 * THIS IS AN EXAMPLE CONTRACT THAT USES UN-AUDITED CODE.
 * DO NOT USE THIS CODE IN PRODUCTION.
 */

//////////////////////////////////
////////////////////////INTERFACES
//////////////////////////////////

interface IFeeManager {
    function getFeeAndReward(
        address subscriber,
        bytes memory report,
        address quoteAddress
    ) external returns (Common.Asset memory, Common.Asset memory, uint256);

    function i_linkAddress() external view returns (address);

    function i_nativeAddress() external view returns (address);

    function i_rewardManager() external view returns (address);
}

interface IVerifierProxy {
    function verify(
        bytes calldata payload,
        bytes calldata parameterPayload
    ) external payable returns (bytes memory verifierResponse);

    function s_feeManager() external view returns (IVerifierFeeManager);
}

//////////////////////////////////
///////////////////END INTERFACES
//////////////////////////////////

contract StreamsLookupChainlinkAutomation is
    ILogAutomation,
    StreamsLookupCompatibleInterface
{
    struct BasicReport {
        bytes32 feedId; // The feed ID the report has data for
        uint32 validFromTimestamp; // Earliest timestamp for which price is applicable
        uint32 observationsTimestamp; // Latest timestamp for which price is applicable
        uint192 nativeFee; // Base cost to validate a transaction using the report, denominated in the chain’s native token (WETH/ETH)
        uint192 linkFee; // Base cost to validate a transaction using the report, denominated in LINK
        uint32 expiresAt; // Latest timestamp where the report can be verified on-chain
        int192 price; // DON consensus median price, carried to 18 decimal places
    }

    struct PremiumReport {
        bytes32 feedId; // The feed ID the report has data for
        uint32 validFromTimestamp; // Earliest timestamp for which price is applicable
        uint32 observationsTimestamp; // Latest timestamp for which price is applicable
        uint192 nativeFee; // Base cost to validate a transaction using the report, denominated in the chain’s native token (WETH/ETH)
        uint192 linkFee; // Base cost to validate a transaction using the report, denominated in LINK
        uint32 expiresAt; // Latest timestamp where the report can be verified on-chain
        int192 price; // DON consensus median price, carried to 18 decimal places
        int192 bid; // Simulated price impact of a buy order up to the X% depth of liquidity utilisation
        int192 ask; // Simulated price impact of a sell order up to the X% depth of liquidity utilisation
    }

    struct Quote {
        address quoteAddress;
    }

    event PriceUpdate(int192 indexed price);

    IVerifierProxy public verifier;

    address public FEE_ADDRESS;
    string public constant STRING_DATASTREAMS_FEEDLABEL = "feedIDs";
    string public constant STRING_DATASTREAMS_QUERYLABEL = "timestamp";
    string[] public feedIds = [
        "0x00027bbaff688c906a3e20a34fe951715d1018d262a5b66e38eda027a674cd1b" // Ex. Basic ETH/USD price report
    ];

    constructor(address _verifier) {
        verifier = IVerifierProxy(_verifier); //Arbitrum Sepolia: 0x2ff010debc1297f19579b4246cad07bd24f2488a
    }

    function checkLog(
        Log calldata log,
        bytes memory
    ) external returns (bool upkeepNeeded, bytes memory performData) {
        revert StreamsLookup(
            STRING_DATASTREAMS_FEEDLABEL,
            feedIds,
            STRING_DATASTREAMS_QUERYLABEL,
            log.timestamp,
            ""
        );
    }

    function checkCallback(
        bytes[] calldata values,
        bytes calldata extraData
    ) external pure returns (bool, bytes memory) {
        bool _upkeepNeeded = true;
        bool success = true;
        bool isError = false;
        return (
            _upkeepNeeded,
            abi.encode(isError, abi.encode(values, extraData, success))
        );
    }

    function checkErrorHandler(
        uint errorCode,
        bytes calldata extraData
    ) public view returns (bool upkeepNeeded, bytes memory performData) {
        bool _upkeepNeeded = true;
        bool success = false;
        bool isError = true;
        // Add custom logic to handle errors offchain here
        if (errorCode == 808400) {
            // Bad request error code
            _upkeepNeeded = false;
        } else {
            // logic to handle other errors
        }
        return (
            _upkeepNeeded,
            abi.encode(isError, abi.encode(errorCode, extraData, success))
        );
    }

    // function will be performed on-chain
    function performUpkeep(bytes calldata performData) external {
        // Decode incoming performData
        (bool isError, bytes memory payload) = abi.decode(
            performData,
            (bool, bytes)
        );

        // Unpacking the errorCode from checkErrorHandler
        if (isError) {
            (uint errorCode, bytes memory extraData, bool reportSuccess) = abi
                .decode(payload, (uint, bytes, bool));

            // Custom logic to handle error codes onchain
        } else {
            // Otherwise unpacking info from checkCallback
            (
                bytes[] memory signedReports,
                bytes memory extraData,
                bool reportSuccess
            ) = abi.decode(payload, (bytes[], bytes, bool));

            if (reportSuccess) {
                bytes memory report = signedReports[0];

                (, bytes memory reportData) = abi.decode(
                    report,
                    (bytes32[3], bytes)
                );

                // Billing

                IFeeManager feeManager = IFeeManager(
                    address(verifier.s_feeManager())
                );
                IRewardManager rewardManager = IRewardManager(
                    address(feeManager.i_rewardManager())
                );

                address feeTokenAddress = feeManager.i_linkAddress();
                (Common.Asset memory fee, , ) = feeManager.getFeeAndReward(
                    address(this),
                    reportData,
                    feeTokenAddress
                );

                IERC20(feeTokenAddress).approve(
                    address(rewardManager),
                    fee.amount
                );

                // Verify the report
                bytes memory verifiedReportData = verifier.verify(
                    report,
                    abi.encode(feeTokenAddress)
                );

                // Decode verified report data into BasicReport struct
                BasicReport memory verifiedReport = abi.decode(
                    verifiedReportData,
                    (BasicReport)
                );

                // Log price from report
                emit PriceUpdate(verifiedReport.price);
            } else {
                // Logic in case reports were not pulled successfully
            }
        }
    }

    fallback() external payable {}
}

What's next

Stay updated on the latest Chainlink news