Skip to content
Verified contractPartialMIT

UkflmsSupplyConsumer

Address0xd1310dcd299b0acf0d7ebe1a390fe23af14a871d
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,329,416
Creation transaction
0x2e6df41977…f6368123ba

src/UkflmsSupplyConsumer.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {ReceiverTemplate} from "./vendor/chainlink-cre/ReceiverTemplate.sol";

/// @title UkflmsSupplyConsumer
/// @notice Stores the circulating supply of UK Financial Moonshot Token (UKFLMS) on its two
///         chains, Robinhood Chain and Solana, as computed by a Chainlink CRE workflow and
///         delivered through the KeystoneForwarder.
///
/// @dev Same design as CirculatingSupplyConsumer. The two tokens are separate (own supplies, own
///      decimals), so each chain has its own circulating supply. The figures are the DON's
///      consensus and are not re-derived: a contract on Ethereum cannot read Solana or Robinhood
///      Chain.
///
///      Naming: block explorers list read functions in ABI order, which the compiler sorts
///      alphabetically with capitals first. The two circulating supplies start with a capital so
///      they are listed first; every other figure is one function returning both chains.
///
///      Ordering of reports: a Solana slot and a Robinhood Chain block cannot be compared with
///      this chain's block number, so reports are ordered by the DON-consensus observation time
///      (strictly increasing), and neither chain's slot or block may move backwards.
///
///      What protects this contract:
///        - only the configured KeystoneForwarder may call `onReport`
///        - only the configured workflow owner, name and ID are accepted (ReceiverTemplate)
///        - reports must be strictly newer than the last accepted one, so replays are rejected
contract UkflmsSupplyConsumer is ReceiverTemplate {
    // ---------------------------------------------------------------------
    // Types
    // ---------------------------------------------------------------------

    struct Snapshot {
        uint256 circulatingSupplyOnRobinhood;
        uint256 circulatingSupplyOnSolana;
        uint256 totalSupplyOnRobinhood;
        uint256 totalSupplyOnSolana;
        uint256 companyBalanceOnRobinhood;
        uint256 companyBalanceOnSolana;
        uint256 ceoBalanceOnSolana;
        uint64 robinhoodBlock;
        uint64 solanaSlot;
        uint64 observedAt;
        uint64 recordedAt;
    }

    /// @dev Grouped so the constructor stays within the stack limit.
    struct Subject {
        string tokenName;
        string tokenSymbol;
        string tokenStandard;
        string solanaToken;
        string solanaCompanyWallet;
        string solanaCeoWallet;
        uint8 solanaDecimals;
        uint256 robinhoodChainId;
        address robinhoodToken;
        address robinhoodCompanyWallet;
        uint8 robinhoodDecimals;
    }

    // ---------------------------------------------------------------------
    // Constants
    // ---------------------------------------------------------------------

    /// @dev Solana has no numeric chain ID; this is the network's label.
    string private constant SOLANA_NETWORK = "solana-mainnet";

    /// @dev abi.encode of: Solana 4 uint256 + uint64, Robinhood 3 uint256 + uint64, observedAt uint64.
    uint256 private constant REPORT_LENGTH = 10 * 32;

    /// @dev Tolerance for DON-consensus clock vs. block timestamp drift.
    uint64 private constant MAX_CLOCK_SKEW = 15 minutes;

    // ---------------------------------------------------------------------
    // The tracked tokens and excluded wallets — set once at deployment
    // ---------------------------------------------------------------------

    uint8 private immutable i_solanaDecimals;
    uint8 private immutable i_robinhoodDecimals;
    uint256 private immutable i_robinhoodChainId;
    address private immutable i_robinhoodToken;
    address private immutable i_robinhoodCompanyWallet;

    /// @dev Solana addresses are base58 strings; strings cannot be `immutable`, but no setter
    ///      exists, so these are fixed for the life of the contract.
    string private s_solanaToken;
    string private s_solanaCompanyWallet;
    string private s_solanaCeoWallet;
    string private s_tokenName;
    string private s_tokenSymbol;

    /// @notice Human-readable label for the token standard. Set once at deployment.
    string public tokenStandard;

    // ---------------------------------------------------------------------
    // State
    // ---------------------------------------------------------------------

    /// @notice Latest circulating supply on Robinhood Chain, in the Robinhood token's base units
    ///         (see `decimals()`).
    uint256 public CirculatingSupplyOnRobinhood;

    /// @notice Latest circulating supply on Solana, in the Solana token's base units
    ///         (see `decimals()`).
    uint256 public CirculatingSupplyOnSolana;

    uint256 private s_totalSupplyOnRobinhood;
    uint256 private s_totalSupplyOnSolana;
    uint256 private s_companyBalanceOnRobinhood;
    uint256 private s_companyBalanceOnSolana;
    uint256 private s_ceoBalanceOnSolana;
    uint64 private s_lastRobinhoodBlock;
    uint64 private s_lastSolanaSlot;

    /// @notice Workflow-reported observation time (DON consensus clock, unix seconds).
    uint64 public lastObservedAt;

    /// @notice `block.timestamp` of the last accepted report.
    uint64 public lastRecordedAt;

    /// @notice Number of reports accepted since deployment.
    uint64 public updateCount;

    /// @notice Advisory freshness window in seconds. Zero disables `isFresh()`.
    uint64 public maxReportAge;

    // ---------------------------------------------------------------------
    // Events
    // ---------------------------------------------------------------------

    event CirculatingSupplyUpdated(
        uint64 indexed observedAt,
        uint256 circulatingSupplyOnRobinhood,
        uint256 circulatingSupplyOnSolana,
        uint64 robinhoodBlock,
        uint64 solanaSlot
    );

    event MaxReportAgeUpdated(uint64 previousMaxReportAge, uint64 newMaxReportAge);

    // ---------------------------------------------------------------------
    // Errors
    // ---------------------------------------------------------------------

    error ZeroAddress();
    error EmptySolanaAddress();
    error DuplicateAddress(address duplicated);
    error DuplicateSolanaWallet();
    error InvalidReportLength(uint256 received, uint256 expected);
    error StaleReport(uint64 observedAt, uint64 lastObservedAt);
    error ObservationInFuture(uint64 observedAt, uint256 currentTime);
    error SolanaSlotRegressed(uint64 reportedSlot, uint64 lastSlot);
    error RobinhoodBlockRegressed(uint64 reportedBlock, uint64 lastBlock);

    // ---------------------------------------------------------------------
    // Construction
    // ---------------------------------------------------------------------

    constructor(address forwarderAddress, Subject memory subject, uint64 initialMaxReportAge)
        ReceiverTemplate(forwarderAddress)
    {
        if (
            bytes(subject.solanaToken).length == 0 || bytes(subject.solanaCompanyWallet).length == 0
                || bytes(subject.solanaCeoWallet).length == 0
        ) revert EmptySolanaAddress();
        if (keccak256(bytes(subject.solanaCompanyWallet)) == keccak256(bytes(subject.solanaCeoWallet))) {
            revert DuplicateSolanaWallet();
        }
        if (subject.robinhoodToken == address(0) || subject.robinhoodCompanyWallet == address(0)) {
            revert ZeroAddress();
        }
        if (subject.robinhoodToken == subject.robinhoodCompanyWallet) {
            revert DuplicateAddress(subject.robinhoodToken);
        }

        s_tokenName = subject.tokenName;
        s_tokenSymbol = subject.tokenSymbol;
        tokenStandard = subject.tokenStandard;
        s_solanaToken = subject.solanaToken;
        s_solanaCompanyWallet = subject.solanaCompanyWallet;
        s_solanaCeoWallet = subject.solanaCeoWallet;
        i_solanaDecimals = subject.solanaDecimals;
        i_robinhoodChainId = subject.robinhoodChainId;
        i_robinhoodToken = subject.robinhoodToken;
        i_robinhoodCompanyWallet = subject.robinhoodCompanyWallet;
        i_robinhoodDecimals = subject.robinhoodDecimals;
        maxReportAge = initialMaxReportAge;

        emit MaxReportAgeUpdated(0, initialMaxReportAge);
    }

    // ---------------------------------------------------------------------
    // Report processing
    // ---------------------------------------------------------------------

    /// @inheritdoc ReceiverTemplate
    /// @dev Called only after the forwarder and workflow-identity checks have passed.
    function _processReport(bytes calldata report) internal override {
        if (report.length != REPORT_LENGTH) {
            revert InvalidReportLength(report.length, REPORT_LENGTH);
        }

        (uint256 solTotal, uint256 solCompany, uint256 solCeo, uint256 solCirculating, uint64 solSlot) =
            abi.decode(report[:160], (uint256, uint256, uint256, uint256, uint64));
        (uint256 rhTotal, uint256 rhCompany, uint256 rhCirculating, uint64 rhBlock, uint64 observedAt) =
            abi.decode(report[160:], (uint256, uint256, uint256, uint64, uint64));

        // --- Freshness ----------------------------------------------------
        if (observedAt <= lastObservedAt) revert StaleReport(observedAt, lastObservedAt);
        if (observedAt > block.timestamp + MAX_CLOCK_SKEW) revert ObservationInFuture(observedAt, block.timestamp);
        if (solSlot < s_lastSolanaSlot) revert SolanaSlotRegressed(solSlot, s_lastSolanaSlot);
        if (rhBlock < s_lastRobinhoodBlock) revert RobinhoodBlockRegressed(rhBlock, s_lastRobinhoodBlock);

        // --- Commit -------------------------------------------------------
        CirculatingSupplyOnRobinhood = rhCirculating;
        CirculatingSupplyOnSolana = solCirculating;
        s_totalSupplyOnRobinhood = rhTotal;
        s_totalSupplyOnSolana = solTotal;
        s_companyBalanceOnRobinhood = rhCompany;
        s_companyBalanceOnSolana = solCompany;
        s_ceoBalanceOnSolana = solCeo;
        s_lastRobinhoodBlock = rhBlock;
        s_lastSolanaSlot = solSlot;
        lastObservedAt = observedAt;
        lastRecordedAt = uint64(block.timestamp);
        unchecked {
            updateCount += 1;
        }

        emit CirculatingSupplyUpdated(observedAt, rhCirculating, solCirculating, rhBlock, solSlot);
    }

    // ---------------------------------------------------------------------
    // Views — one function per item, Robinhood Chain first, then Solana
    // ---------------------------------------------------------------------

    /// @notice Total supply on each chain, in each token's base units.
    function totalSupply() external view returns (uint256 robinhood, uint256 solana) {
        return (s_totalSupplyOnRobinhood, s_totalSupplyOnSolana);
    }

    /// @notice Company wallet balance on each chain, excluded from circulating supply.
    function companyBalance() external view returns (uint256 robinhood, uint256 solana) {
        return (s_companyBalanceOnRobinhood, s_companyBalanceOnSolana);
    }

    /// @notice CEO wallet balance on Solana, excluded from circulating supply. (No CEO wallet is
    ///         excluded on Robinhood Chain.)
    function ceoBalance() external view returns (uint256 solana) {
        return s_ceoBalanceOnSolana;
    }

    /// @notice Decimals of each chain's token.
    function decimals() external view returns (uint8 robinhood, uint8 solana) {
        return (i_robinhoodDecimals, i_solanaDecimals);
    }

    /// @notice Robinhood Chain's chain ID, and Solana's network (Solana has no numeric chain ID).
    function chainIds() external view returns (uint256 robinhood, string memory solana) {
        return (i_robinhoodChainId, SOLANA_NETWORK);
    }

    /// @notice The Robinhood Chain block and Solana slot the latest observation was taken at.
    function lastObservedBlocks() external view returns (uint64 robinhoodBlock, uint64 solanaSlot) {
        return (s_lastRobinhoodBlock, s_lastSolanaSlot);
    }

    /// @notice The tracked token, grouped so a block explorer shows it together.
    /// @return name The token's name
    /// @return symbol The token's symbol
    /// @return robinhoodToken The token on Robinhood Chain
    /// @return solanaToken The token's mint on Solana (base58)
    /// @return standard The token standard label set at deployment
    function tokenInfo()
        external
        view
        returns (
            string memory name,
            string memory symbol,
            address robinhoodToken,
            string memory solanaToken,
            string memory standard
        )
    {
        return (s_tokenName, s_tokenSymbol, i_robinhoodToken, s_solanaToken, tokenStandard);
    }

    /// @notice The wallets excluded from circulating supply, grouped for readability.
    function excludedWallets()
        external
        view
        returns (address robinhoodCompany, string memory solanaCompany, string memory solanaCeo)
    {
        return (i_robinhoodCompanyWallet, s_solanaCompanyWallet, s_solanaCeoWallet);
    }

    /// @notice Returns the full latest observation in a single call.
    function latestSnapshot() external view returns (Snapshot memory) {
        return Snapshot({
            circulatingSupplyOnRobinhood: CirculatingSupplyOnRobinhood,
            circulatingSupplyOnSolana: CirculatingSupplyOnSolana,
            totalSupplyOnRobinhood: s_totalSupplyOnRobinhood,
            totalSupplyOnSolana: s_totalSupplyOnSolana,
            companyBalanceOnRobinhood: s_companyBalanceOnRobinhood,
            companyBalanceOnSolana: s_companyBalanceOnSolana,
            ceoBalanceOnSolana: s_ceoBalanceOnSolana,
            robinhoodBlock: s_lastRobinhoodBlock,
            solanaSlot: s_lastSolanaSlot,
            observedAt: lastObservedAt,
            recordedAt: lastRecordedAt
        });
    }

    /// @notice Whether at least one report has been accepted and it is within `maxReportAge`.
    /// @dev Integrators should gate on this rather than reading the supply blindly, since an
    ///      un-updated contract would otherwise read as a circulating supply of zero.
    function isFresh() external view returns (bool) {
        if (updateCount == 0) return false;
        if (maxReportAge == 0) return true;
        return block.timestamp - lastRecordedAt <= maxReportAge;
    }

    // ---------------------------------------------------------------------
    // Admin
    // ---------------------------------------------------------------------

    /// @notice Sets the advisory freshness window used by `isFresh()`.
    function setMaxReportAge(uint64 newMaxReportAge) external onlyOwner {
        uint64 previous = maxReportAge;
        maxReportAge = newMaxReportAge;
        emit MaxReportAgeUpdated(previous, newMaxReportAge);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

src/vendor/chainlink-cre/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
  /**
   * @dev Returns true if this contract implements the interface defined by
   * `interfaceId`. See the corresponding
   * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
   * to learn more about how these ids are created.
   *
   * This function call must use less than 30 000 gas.
   */
  function supportsInterface(
    bytes4 interfaceId
  ) external view returns (bool);
}

src/vendor/chainlink-cre/IReceiver.sol

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

import {IERC165} from "./IERC165.sol";

/// @title IReceiver - receives keystone reports
/// @notice Implementations must support the IReceiver interface through ERC165.
interface IReceiver is IERC165 {
  /// @notice Handles incoming keystone reports.
  /// @dev If this function call reverts, it can be retried with a higher gas
  /// limit. The receiver is responsible for discarding stale reports.
  /// @param metadata Report's metadata.
  /// @param report Workflow report.
  function onReport(
    bytes calldata metadata,
    bytes calldata report
  ) external;
}

src/vendor/chainlink-cre/ReceiverTemplate.sol

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

import {IERC165} from "./IERC165.sol";
import {IReceiver} from "./IReceiver.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

/// @title ReceiverTemplate - Abstract receiver with optional permission controls
/// @notice Provides flexible, updatable security checks for receiving workflow reports
/// @dev The forwarder address is required at construction time for security.
///      Additional permission fields can be configured using setter functions.
abstract contract ReceiverTemplate is IReceiver, Ownable {
    // Required permission field at deployment, configurable after
    address private s_forwarderAddress; // Only this address can call onReport

    // Optional permission fields (all default to zero = disabled)
    address private s_expectedAuthor; // If set, only reports from this workflow owner are accepted
    bytes10 private s_expectedWorkflowName; // Only validated when s_expectedAuthor is also set
    bytes32 private s_expectedWorkflowId; // If set, only reports from this specific workflow ID are accepted

    /// @dev The plaintext workflow name, kept for HUMAN READABILITY ONLY and never used in any
    ///      check. `s_expectedWorkflowName` above stores sha256(name) truncated to 10 hex
    ///      characters, which is what the Forwarder sends and what is actually compared. That
    ///      fingerprint is one-way, so without this the name can never be displayed — block
    ///      explorers would only ever show bytes like 0x61663761356138393239.
    string private s_expectedWorkflowNameText;

    // Hex character lookup table for bytes-to-hex conversion
    bytes private constant HEX_CHARS = "0123456789abcdef";
    uint256 private constant METADATA_LENGTH = 64;

    // Custom errors
    error InvalidForwarderAddress();
    error InvalidSender(address sender, address expected);
    error InvalidAuthor(address received, address expected);
    error InvalidWorkflowName(bytes10 received, bytes10 expected);
    error InvalidWorkflowId(bytes32 received, bytes32 expected);
    error WorkflowNameRequiresAuthorValidation();
    error InvalidMetadataLength(uint256 received, uint256 expected);

    // Events
    event ForwarderAddressUpdated(address indexed previousForwarder, address indexed newForwarder);
    event ExpectedAuthorUpdated(address indexed previousAuthor, address indexed newAuthor);
    event ExpectedWorkflowNameUpdated(bytes10 indexed previousName, bytes10 indexed newName);
    event ExpectedWorkflowIdUpdated(bytes32 indexed previousId, bytes32 indexed newId);
    /// @notice Constructor sets msg.sender as the owner and configures the forwarder address
    /// @param _forwarderAddress The address of the Chainlink Forwarder contract (cannot be address(0))
    /// @dev The forwarder address is required for security - it ensures only verified reports are processed
    constructor(address _forwarderAddress) Ownable(msg.sender) {
        if (_forwarderAddress == address(0)) {
            revert InvalidForwarderAddress();
        }
        s_forwarderAddress = _forwarderAddress;
        emit ForwarderAddressUpdated(address(0), _forwarderAddress);
    }

    /// @notice Returns the configured forwarder address
    /// @return The forwarder address
    function getForwarderAddress() external view returns (address) {
        return s_forwarderAddress;
    }

    /// @notice Returns the expected workflow author address
    /// @return The expected author address (address(0) if not set)
    function getExpectedAuthor() external view returns (address) {
        return s_expectedAuthor;
    }

    /// @notice Returns the expected workflow name
    /// @return The expected workflow name (bytes10(0) if not set)
    function getExpectedWorkflowName() external view returns (bytes10) {
        return s_expectedWorkflowName;
    }

    /// @notice Returns the expected workflow ID
    /// @return The expected workflow ID (bytes32(0) if not set)
    function getExpectedWorkflowId() external view returns (bytes32) {
        return s_expectedWorkflowId;
    }

    /// @inheritdoc IReceiver
    /// @dev Performs optional validation checks based on which permission fields are set
    function onReport(bytes calldata metadata, bytes calldata report) external override {
        // Security Check 1: Verify caller is the trusted Chainlink Forwarder (if configured)
        if (msg.sender != s_forwarderAddress) {
            revert InvalidSender(msg.sender, s_forwarderAddress);
        }

        // Security Checks 2-4: Verify workflow identity - ID, owner, and/or name (if any are configured)
        if (
            s_expectedWorkflowId != bytes32(0) || s_expectedAuthor != address(0) || s_expectedWorkflowName != bytes10(0)
        ) {
            (bytes32 workflowId, bytes10 workflowName, address workflowOwner) = _decodeMetadata(metadata);

            if (s_expectedWorkflowId != bytes32(0) && workflowId != s_expectedWorkflowId) {
                revert InvalidWorkflowId(workflowId, s_expectedWorkflowId);
            }
            if (s_expectedAuthor != address(0) && workflowOwner != s_expectedAuthor) {
                revert InvalidAuthor(workflowOwner, s_expectedAuthor);
            }

            // ================================================================
            // WORKFLOW NAME VALIDATION - REQUIRES AUTHOR VALIDATION
            // ================================================================
            // Do not rely on workflow name validation alone. Workflow names are unique
            // per owner, but not across owners.
            // Furthermore, workflow names use 40-bit truncation (bytes10), making collisions possible.
            // Therefore, workflow name validation REQUIRES author (workflow owner) validation.
            // The code enforces this dependency at runtime.
            // ================================================================
            if (s_expectedWorkflowName != bytes10(0)) {
                // Author must be configured if workflow name is used
                if (s_expectedAuthor == address(0)) {
                    revert WorkflowNameRequiresAuthorValidation();
                }
                // Validate workflow name matches (author already validated above)
                if (workflowName != s_expectedWorkflowName) {
                    revert InvalidWorkflowName(workflowName, s_expectedWorkflowName);
                }
            }
        }

        _processReport(report);
    }

    /// @notice Updates the forwarder address that is allowed to call onReport
    /// @param _forwarder The new forwarder address
    /// @dev The forwarder address cannot be set to address(0). Without this check, anyone can call
    ///      onReport() with arbitrary data.
    function setForwarderAddress(address _forwarder) external onlyOwner {
        if (_forwarder == address(0)) {
            revert InvalidForwarderAddress();
        }

        address previousForwarder = s_forwarderAddress;
        s_forwarderAddress = _forwarder;
        emit ForwarderAddressUpdated(previousForwarder, _forwarder);
    }

    /// @notice Updates the expected workflow owner address
    /// @param _author The new expected author address (use address(0) to disable this check)
    function setExpectedAuthor(address _author) external onlyOwner {
        if (_author == address(0) && s_expectedWorkflowName != bytes10(0)) {
            revert WorkflowNameRequiresAuthorValidation();
        }

        address previousAuthor = s_expectedAuthor;
        s_expectedAuthor = _author;
        emit ExpectedAuthorUpdated(previousAuthor, _author);
    }

    /// @notice Updates the expected workflow name from a plaintext string
    /// @param _name The workflow name as a string (use empty string "" to disable this check)
    /// @dev IMPORTANT: Workflow name validation REQUIRES author validation to be enabled.
    ///      The workflow name uses only 40-bit truncation, making collision attacks feasible
    ///      when used alone. However, since workflow names are unique per owner, validating
    ///      both the name AND the author address provides adequate security.
    ///      You must call setExpectedAuthor() before calling this function.
    ///      The name is hashed using SHA256 and truncated to bytes10.
    function setExpectedWorkflowName(string calldata _name) external onlyOwner {
        bytes10 previousName = s_expectedWorkflowName;

        if (bytes(_name).length == 0) {
            s_expectedWorkflowName = bytes10(0);
            s_expectedWorkflowNameText = "";
            emit ExpectedWorkflowNameUpdated(previousName, bytes10(0));
            return;
        }

        if (s_expectedAuthor == address(0)) {
            revert WorkflowNameRequiresAuthorValidation();
        }

        // Convert workflow name to bytes10:
        // SHA256 hash → hex encode → take first 10 chars → hex encode those chars
        bytes32 hash = sha256(bytes(_name));
        bytes memory hexString = _bytesToHexString(abi.encodePacked(hash));
        bytes memory first10 = new bytes(10);
        for (uint256 i = 0; i < 10; i++) {
            first10[i] = hexString[i];
        }
        s_expectedWorkflowName = bytes10(first10);
        s_expectedWorkflowNameText = _name;
        emit ExpectedWorkflowNameUpdated(previousName, s_expectedWorkflowName);
    }

    /// @notice The workflow identity checks, grouped so a block explorer shows them together.
    /// @return author The workflow owner that must have produced the report (0x0 = check off)
    /// @return workflowId The exact workflow ID required (0x0 = check off)
    /// @return workflowNameFingerprint The 10-byte value actually compared against the report
    /// @return workflowNameText The same name in plain text, for reading only
    function workflowIdentity()
        external
        view
        returns (address author, bytes32 workflowId, bytes10 workflowNameFingerprint, string memory workflowNameText)
    {
        return (s_expectedAuthor, s_expectedWorkflowId, s_expectedWorkflowName, s_expectedWorkflowNameText);
    }

    /// @notice The plaintext workflow name. Display only; never used in any check.
    function getExpectedWorkflowNameText() external view returns (string memory) {
        return s_expectedWorkflowNameText;
    }

    /// @notice Updates the expected workflow ID
    /// @param _id The new expected workflow ID (use bytes32(0) to disable this check)
    function setExpectedWorkflowId(bytes32 _id) external onlyOwner {
        bytes32 previousId = s_expectedWorkflowId;
        s_expectedWorkflowId = _id;
        emit ExpectedWorkflowIdUpdated(previousId, _id);
    }

    /// @notice Helper function to convert bytes to hex string
    /// @param data The bytes to convert
    /// @return The hex string representation
    function _bytesToHexString(bytes memory data) private pure returns (bytes memory) {
        bytes memory hexString = new bytes(data.length * 2);

        for (uint256 i = 0; i < data.length; i++) {
            hexString[i * 2] = HEX_CHARS[uint8(data[i] >> 4)];
            hexString[i * 2 + 1] = HEX_CHARS[uint8(data[i] & 0x0f)];
        }

        return hexString;
    }

    /// @notice Extracts all metadata fields from the onReport metadata parameter
    /// @param metadata The metadata bytes encoded using abi.encodePacked(workflowId, workflowName, workflowOwner)
    /// @return workflowId The unique identifier of the workflow (bytes32)
    /// @return workflowName The name of the workflow (bytes10)
    /// @return workflowOwner The owner address of the workflow
    function _decodeMetadata(bytes memory metadata)
        internal
        pure
        returns (bytes32 workflowId, bytes10 workflowName, address workflowOwner)
    {
        if (metadata.length != METADATA_LENGTH) {
            revert InvalidMetadataLength(metadata.length, METADATA_LENGTH);
        }

        // Metadata structure (encoded using abi.encodePacked by the Forwarder):
        // - Offset 0, size 32: workflow_id (bytes32)
        // - Offset 32, size 10: workflow_name (bytes10)
        // - Offset 42, size 20: workflow_owner (address)
        assembly {
            workflowId := mload(add(metadata, 32))
            workflowName := mload(add(metadata, 64))
            workflowOwner := shr(mul(12, 8), mload(add(metadata, 74)))
        }
        return (workflowId, workflowName, workflowOwner);
    }

    /// @notice Abstract function to process the report data
    /// @param report The report calldata containing your workflow's encoded data
    /// @dev Implement this function with your contract's business logic
    function _processReport(bytes calldata report) internal virtual;

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IReceiver).interfaceId || interfaceId == type(IERC165).interfaceId;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 1000000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.